user10717010
user10717010

Reputation:

Why doesn't the generator return the following value?

For each call to the "loop" function, I try to return a new value of the "c" property from the "test" object, but for some reason, I get the same value of every function call.

1 call: {value: {a: 1}, done: false}
2 call: {value: {a: 1}, executed: false}
3 call: {value: {a: 1}, done: false}

instead of getting a new value for every call

1 call: {value: {a: 1}, done: false}
2 call: {value: {a: 2}, executed: false}
3 call: {value: {a: 3}, done: true}

const test = {
  a: { id: 1 },
  b: { id: 2 },
  c: [{ a: 1 }, { a: 2 }, { c: 3 }]
};

function* generLoop(elem) {
  // eslint-disable-next-line no-undef,no-restricted-syntax
  for (el of test[elem]) {
    // eslint-disable-next-line no-undef
    yield el;
  }
}

const createLoop = elem => {
  const gen = generLoop(elem);
  return () => gen.next();
};

function loop(elem) {
  const findQuery = Object.keys(test).find(el => el === elem);
  if (findQuery) {
    const loopIterator = createLoop('c');
    loopIterator();
  }
  return test[elem];
}

for (let i = 0; i < 3; i++) {
  console.log(loop('c'));
}

In fact, this is a simulation of the logic that I want to implement. In reality, I imitate the response of the server when the names of the requests come, I want to give a certain set of data, but some requests will come several times and ask for the same data structure but with different values, so the function "loop" will be called independently.

Upvotes: 2

Views: 58

Answers (1)

Max
Max

Reputation: 2036

You have to create a generator only once, and then call next() as you need

cosnt createLoop = elem => {
  const findQuery = Object.keys(test).find(el => el === elem);
  let gen
  if (findQuery) {
    gen = generLoop('c');
  }
  return () => gen ? gen.next() : test[elem];
}

const iterator = createLoop('c')
for (let i = 0; i < 3; i++) {
  console.log(iterator());
}

Upvotes: 2

Related Questions