Sub topic 2
Handling Errors in Async Loops
This chapter assumes you know Promises, async/await, try/catch, and the basics of for await...of and async function*.
Catching Errors from the Source
An async iterator can fail in two ways. An async generator can throw, or a hand-written next() can return a rejected promise. Both failures reach the loop as an exception, so an ordinary try/catch around the loop catches them.
async function* failing() {
yield 1;
throw new Error('source failed');
}
async function main() {
try {
for await (const value of failing()) {
console.log(value);
}
} catch (err) {
console.error('Caught:', err.message);
}
}
main(); // 1, then Caught: source failedAfter a generator throws, it is finished. Any later next() call returns { done: true }.
Breaking Out Early and Cleaning Up
If the loop exits through break, return, or an exception in the loop body, for await...of calls the iterator's return() method. For a generator, that runs its finally block, which makes finally the right place to close files or connections.
async function* openResource() {
console.log('open');
try {
yield 'a';
yield 'b';
} finally {
console.log('close');
}
}
async function main() {
for await (const item of openResource()) {
console.log(item);
if (item === 'a') break;
}
}
main(); // open, a, closeBuilding an Async Iterable by Hand
A hand-built async iterable is an object with a [Symbol.asyncIterator]() method. That method returns an object whose next() returns a Promise of { value, done }. Add return() if the iterable needs cleanup on early exit.
const ticker = {
[Symbol.asyncIterator]() {
let count = 0;
return {
next() {
count++;
if (count > 3) return Promise.resolve({ value: undefined, done: true });
return new Promise((r) =>
setTimeout(() => r({ value: count, done: false }), 100));
},
return() {
console.log('cleanup');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
for await (const tick of ticker) {
console.log(tick);
if (tick === 2) break; // logs 'cleanup'
}
}
main();for await...of over Sync Iterables and Promise Arrays
for await...of also accepts sync iterables. It awaits each value in turn, so an array of promises produces their results in array order.
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
async function main() {
for await (const v of [delay(200, 'a'), delay(100, 'b')]) {
console.log(v); // a, b
}
}
main();Exercise
A loop over an async generator throws an error inside the loop body (not in the generator). Does the generator's finally block run?
Show answer
Yes. An exception in the loop body exits the loop early, so for await...of calls the iterator's return() method, and that runs the generator's finally block before the error propagates.