Sub topic 5
Handling Errors in Async Loops
This chapter assumes you know async/await, try/catch, and the for await...of loop and async generators from the previous chapters. It covers where errors come from during async iteration, how they reach your loop, and how to keep a loop running when a single item fails.
Where errors come from
Errors during async iteration can come from three places:
| Source | Example | What the loop sees |
|---|---|---|
| The async generator body | `throw new Error()` after a `yield` | The pending `next()` promise rejects |
| A hand-written iterator | `next()` returns a rejected promise | The same rejection |
| Your loop body | Your own code throws | The loop exits and calls `return()` on the iterator |
In the first two cases, for await...of awaits each next() result. When that promise rejects, the await throws at the loop. So an ordinary try/catch around the loop catches it, just as it would around a single await.
Catching an error from a generator
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 failedThe loop body runs once for 1. The second next() call resumes the generator, the generator throws, and control jumps to catch. The generator is now finished. If you called next() on it again you would get { value: undefined, done: true }, and the generator would not resume.
Rejections from a hand-written iterator
A hand-written iterator reports failure by returning a rejected promise from next():
const flaky = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
i++;
if (i === 3) {
return Promise.reject(new Error('network down'));
}
return Promise.resolve({ value: i, done: false });
}
};
}
};
async function main() {
try {
for await (const n of flaky) {
console.log(n);
}
} catch (err) {
console.error('Caught:', err.message);
}
}
main(); // 1, 2, then Caught: network downRecovering per item
A try/catch around the whole loop stops the entire iteration at the first failure. To skip bad items and keep going, catch the error inside the generator and yield a result object in its place:
const load = (id) =>
new Promise((resolve, reject) =>
setTimeout(() => {
if (id === 2) reject(new Error(`item ${id} missing`));
else resolve({ id, name: `Item ${id}` });
}, 50)
);
async function* loadAll(ids) {
for (const id of ids) {
try {
yield { ok: true, data: await load(id) };
} catch (err) {
yield { ok: false, id, error: err.message };
}
}
}
async function main() {
for await (const result of loadAll([1, 2, 3])) {
if (result.ok) console.log('Loaded', result.data.name);
else console.warn('Skipped', result.id, '-', result.error);
}
}
main(); // Loaded Item 1, Skipped 2 - item 2 missing, Loaded Item 3Because the generator catches each failure itself, it never rejects, and the loop runs to the end.
Common mistakes
- No handler at all. If
main()has notry/catchand you call it without.catch(), the rejection becomes an unhandled promise rejection. Node.js crashes the process by default when that happens. Writemain().catch(console.error)as a safety net. - Expecting the generator to resume. Once a generator throws an error it does not catch, it is finished. Restarting means calling the generator function again.
- Wrapping only the loop body. A
try/catchinside the loop body catches errors from your own code but not rejections fromnext(). Those happen in the loop header, outside the body.
Exercise
You wrap only the body of a for await...of loop in try/catch, and the async generator throws on its third item. Does your catch block run, and what happens to the loop?
Show answer
No. The error comes from next(), which the loop header awaits outside the body's try block. The rejection exits the loop and propagates to the enclosing function. You need a try/catch around the whole loop, or the generator must catch the error itself and yield a result object instead.
Exercise
How would you change loadAll so that it stops after the first failure, yields nothing for the failed item, and still lets the caller see the error?
Show answer
Remove the try/catch inside loadAll and write yield await load(id). The rejection then propagates out of the generator, the generator finishes, and the caller's try/catch around the loop receives the error.