Search code examples
javascriptasync-awaitgeneratoryield

Is "yield await" redundant in JavaScript async generator functions?


Promises yielded within async function* declarations seem to be automatically awaited before the iterator result is sent to the caller (source: MDN). Does this mean that yield await somePromise is redundant and yield somePromise will produce the same behavior in all cases? Or, are there exceptions to watch out for?

P.S. I thought there might be some behavioral differences related to error handling contexts and try/catch. From my experimentation though, it seems that a promise yielded in a try block will always be caught and handled within the async generator, regardless if there is an explicit await.


Solution

  • The await is quite redundant here. Using await also delays the resolve timing in the microtask queue.

    Promise.resolve()
      .then(() => console.log(1))
      .then(() => console.log(2))
      .then(() => console.log(3))
      .then(() => console.log(4))
      .then(() => console.log(5));
      
    (async () => {
      const func = async function*() {
        yield await Promise.resolve('yield await');
      };
      
      for await (let i of func()) {
          console.log(i);
      }
    })();

    Promise.resolve()
      .then(() => console.log(1))
      .then(() => console.log(2))
      .then(() => console.log(3))
      .then(() => console.log(4))
      .then(() => console.log(5));
      
    (async () => {
      const func = async function*() {
        yield Promise.resolve('yield');
      };
      
      for await (let i of func()) {
          console.log(i);
      }
    })();