Generator return doesn't work in for-await-of loop

Viewed 218

Generator with return statement skips the execution of for-await-of loop.

(async () => {
  const gen = async function* () {
     return { newState: "FAILURE" };
  };
  for await (const { newState } of gen()) {
    console.log("Yey! new state is:", newState);
    // do other stuff
  }
})();

In the case written above, the whole for-await-of construction will never console.log anything. But when you swap return for yield (yield { newState: 'FAILURE' }) everything work as intended.

(async () => {
  const gen = async function* () {
    yield { newState: "FAILURE" };
  };
  for await (const { newState } of gen()) {
    console.log("Yey! new state is:", newState);
    // do other stuff
  }
})();

WHY?

1 Answers

The iterator never yielded anything before completing, so the loop didn't have anything to iterate - the sequence was empty. Notice you can yield multiple times but return only once.

A for … of loop ignores the return value of an iterator. It's only useful when you are manually advancing the iterator, or when using yield*.

async function* generate() {
  return { newState: "FAILURE" };
};
const generator = (async function*() {
  const { newState } = yield* generate()
  console.log("Yey! new state is:", newState);
  return "some value";
})();
generator.next().then(console.log);

This is no different for asynchronous iterators than for synchronous iterators.

Related