1

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.

1
  • 1
    Yes Commented Aug 31, 2023 at 1:31

1 Answer 1

2

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);
  }
})();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.