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.
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();1 2 caught: stop done
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.