Sub topic 5
Handling Errors in Async Loops
This chapter assumes you know how for await...of consumes an async iterable and how async function* produces one. You should also be comfortable with try/catch around await. The goal is a working model of three things: where errors can start during async iteration, where they show up, and which ones a loop can survive.
Where Errors Come From
When a for await...of loop runs, an error can come from one of three places:
- The source. An async generator throws, or an
awaitinside it rejects and nothing catches it there. - The iterator protocol itself. A hand-written
next()rejects, throws, or resolves to something that is not an object. - The loop body. Your own code between the braces throws.
All three end the loop. They differ in where you can catch them and in whether the iterator gets a chance to clean up.
Errors from the Source Surface at the Loop
An async generator that throws rejects the promise returned by its next() call. for await...of awaits that promise, so the rejection is rethrown at the loop statement. That means an ordinary try/catch around the loop catches it:
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 same thing happens when an await inside the generator rejects, for example a failed fetch. To the consumer, an uncaught rejection inside the generator looks exactly like a throw.
A failed generator is finished
When an async generator throws, it moves to its completed state for good. Any later next() call resolves to { value: undefined, done: true }. It cannot pick up where it stopped:
async function* failing() {
yield 1;
throw new Error('source failed');
}
async function main() {
const gen = failing();
console.log(await gen.next()); // { value: 1, done: false }
try {
await gen.next();
} catch (err) {
console.log('Caught:', err.message); // Caught: source failed
}
console.log(await gen.next()); // { value: undefined, done: true }
}
main();This matters when you plan to retry. Running for await...of again over the same generator object yields nothing. To try again you have to call the generator function again and get a new generator. Better still, handle the failure inside the generator before it escapes, as shown below.
Where You Put try/catch Decides What You Catch
A try/catch inside the loop body only sees errors thrown by the body. Source errors are thrown at the loop header, which is outside that inner try. Each placement catches a different kind of error:
async function* numbers() {
yield 1;
yield 2;
throw new Error('source failed');
}
async function main() {
try {
for await (const n of numbers()) {
try {
if (n === 1) throw new Error('bad item');
console.log('processed', n);
} catch (err) {
console.log('skipped', n, '-', err.message);
}
}
} catch (err) {
console.log('loop ended:', err.message);
}
}
main();
// skipped 1 - bad item
// processed 2
// loop ended: source failed| Placement | Catches | Loop keeps going? |
|---|---|---|
| Inside the loop body | Errors thrown by your per-item code | Yes |
| Around the whole loop | Source errors, protocol errors, uncaught body errors | No, the loop is already over |
| Inside the generator | Errors from the generator's own `await` calls | Yes, if the generator keeps yielding |
Body Errors Close the Iterator
If the loop body throws and the body does not catch it, for await...of calls the iterator's return() method and waits for it before passing the error on. For an async generator, that runs any pending finally blocks:
async function* source() {
try {
yield 1;
yield 2;
} finally {
console.log('source cleaned up');
}
}
async function main() {
try {
for await (const n of source()) {
throw new Error(`body failed on ${n}`);
}
} catch (err) {
console.log('Caught:', err.message);
}
}
main();
// source cleaned up
// Caught: body failed on 1The cleanup line prints first. The loop finishes closing the source before your catch block runs. The original error is the one that propagates. If return() throws too, its error is thrown away and you still see the body's error. The next chapter covers return() and finally in full. For error handling, the rule to remember is that body errors close the source.
Protocol Errors Do Not Close the Iterator
The opposite holds when next() itself fails. If next() throws, rejects, or resolves to a value that is not an object, the loop treats the iterator as broken and does not call return():
const flaky = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
i++;
if (i === 2) return Promise.reject(new Error('network down'));
return Promise.resolve({ value: i, done: false });
},
return() {
console.log('return() called');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
try {
for await (const v of flaky) {
console.log(v);
}
} catch (err) {
console.log('Caught:', err.message);
}
}
main();
// 1
// Caught: network downreturn() called never prints. When you write an iterator by hand, release its resources before you reject from next(). Nobody will call return() for you afterward. Async generators avoid this problem: when an error leaves the generator body, its finally blocks have already run on the way out.
If next() resolves to a non-object, such as resolve(42), the loop throws a TypeError along the lines of "Iterator result 42 is not an object". This is a common bug in hand-written iterators that forget the { value, done } wrapper.
Recovering Inside the Generator
The generator is the only place where a failure can be handled without ending the sequence. One pattern is to catch each step's error and yield a result object in place of the value:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* runAll(tasks) {
for (const task of tasks) {
let result;
try {
result = { ok: true, value: await task() };
} catch (error) {
result = { ok: false, error };
}
yield result;
}
}
const tasks = [
async () => { await sleep(50); return 'first'; },
async () => { await sleep(50); throw new Error('second broke'); },
async () => { await sleep(50); return 'third'; }
];
async function main() {
for await (const r of runAll(tasks)) {
console.log(r.ok ? `ok: ${r.value}` : `failed: ${r.error.message}`);
}
}
main();
// ok: first
// failed: second broke
// ok: thirdThe yield sits outside the try on purpose. If it were inside, a break in the consumer would still work, because return() is not caught by catch. But a consumer calling gen.throw() would have its error caught and turned into a "failed task" result, which is rarely what you want. Keep the try around the work and nothing else.
Retrying a step
You can also retry inside the generator, because the generator does not end until an error leaves it:
async function retry(fn, attempts) {
let lastError;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
}
}
throw lastError;
}
async function* pages(loadPage, count) {
for (let n = 1; n <= count; n++) {
yield await retry(() => loadPage(n), 3);
}
}
let calls = 0;
async function loadPage(n) {
calls++;
if (calls === 2) throw new Error('timeout'); // fails once
return `page ${n}`;
}
async function main() {
for await (const p of pages(loadPage, 3)) {
console.log(p);
}
}
main(); // page 1, page 2, page 3If all three attempts fail, retry throws, the error leaves the generator, and the consumer's outer try/catch handles it like any other source error.
Yielding a rejected promise
In an async generator, yield awaits its operand. yield somePromise waits for the promise to settle. If it rejects, the error is thrown at that yield inside the generator, not passed to the consumer as a value. You can catch it there:
async function* demo() {
try {
yield Promise.reject(new Error('rejected value'));
} catch (err) {
console.log('generator caught:', err.message);
yield 'fallback';
}
}
async function main() {
for await (const v of demo()) console.log(v);
}
main();
// generator caught: rejected value
// fallbackDo Not Lose the Error at the Top
A for await...of loop runs inside an async function or at the top level of a module. If the error leaves that function, the function's promise rejects. When nothing handles that promise, Node.js reports an unhandled rejection, and since Node 15 the process exits with code 1. Browsers log it to the console.
async function* failing() {
yield 1;
throw new Error('source failed');
}
async function main() {
for await (const v of failing()) console.log(v);
}
main().catch((err) => {
console.error('Fatal:', err.message);
process.exitCode = 1;
});Wrapping the call in a synchronous try { main(); } catch {} does nothing. main() returns a promise straight away, and the rejection comes later. Attach .catch() to the promise or await it. In an ES module that uses top-level for await, an uncaught error rejects the module's evaluation, and Node reports it and exits.
Quick Reference
| Error origin | Surfaces at | `return()` called? | Can the loop continue? |
|---|---|---|---|
| Generator throws or its `await` rejects (uncaught) | `for await` header | No, generator already finished | No |
| Manual `next()` rejects or throws | `for await` header | No | No |
| `next()` resolves to a non-object | `for await` header as `TypeError` | No | No |
| Loop body throws, not caught in the body | Out of the loop | Yes | No |
| Loop body throws, caught in the body | Inner `catch` | No | Yes |
| Caught inside the generator | Nowhere (handled) | No | Yes |
Exercise
An async generator yields 'a', then awaits a fetch that rejects. The consumer wraps only the loop body in try/catch and logs each item. What gets logged, and what happens to the error?
Show answer
'a' is logged. The rejection is thrown at the for await header, which is outside the body's try/catch, so the inner catch never runs. The error leaves the loop and rejects the enclosing async function. If that promise is not handled, it becomes an unhandled rejection. A try/catch around the whole loop is needed to catch it.
Exercise
A hand-written async iterator opens a database cursor in Symbol.asyncIterator() and closes it in return(). Its next() rejects when a query fails. Why can the cursor leak, and how do you fix it?
Show answer
When next() rejects, for await...of treats the iterator as broken and does not call return(), so the close code in return() never runs. Fix it by closing the cursor inside next() before rejecting, for example with a try/catch or finally around the query. Or rewrite the iterator as an async generator with a try/finally, because the finally runs when the error leaves the generator.
Exercise
You want to process 100 URLs with for await...of, keep going when individual requests fail, and print a list of failures at the end. Where should the error handling go?
Show answer
Inside the generator, around each await, turning each outcome into a result object such as { ok: true, value } or { ok: false, error, url } and yielding it. The consumer collects the failed results into an array and prints them after the loop. An outer try/catch can still guard against unexpected errors that end the run.