πŸ”΄ HardEvent Loop & PromisesπŸ’» Output Question

Promise rejection in async generator

πŸ’‘

Hint

Errors thrown inside async generators are caught by try/catch wrapping the for await...of loop, just like synchronous for...of with regular generators.

What does this output?

async function* generate() {
  yield 1;
  yield 2;
  throw new Error('stop');
  yield 3;
}

async function run() {
  try {
    for await (const val of generate()) {
      console.log(val);
    }
  } catch (e) {
    console.log('caught:', e.message);
  }
  console.log('done');
}

run();

Correct Output

1
2
caught: stop
done

Why this output?

Explanation: Async generator yields 1 and 2 normally. On third iteration, throws β€” the for await...of loop propagates the error to the try/catch. "done" runs after the catch.

Key Insight: Errors thrown inside async generators are caught by try/catch wrapping the for await...of loop, just like synchronous for...of with regular generators.

More Event Loop & Promises Output Questions

🟑 MediumClassic setTimeout vs Promiseβ†’πŸ”΄ HardNested setTimeout and Promiseβ†’πŸŸ‘ Mediumasync/await execution orderβ†’πŸ”΄ HardPromise chaining orderβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz