Sub topic 6
Breaking Out Early and Cleaning Up
This chapter assumes you know how for await...of consumes an async iterable and how to write an async function*. It also assumes you are comfortable with try/finally.
A loop does not always run until the source is exhausted. You might break once you find a match, return from the enclosing function, or throw from the loop body. If the source holds a file handle, a network connection, or a database cursor, that resource still has to be released. The async iteration protocol handles this with an optional iterator method called return().
What the loop does when you leave early
When a for await...of loop exits before the iterator reports done: true, the loop calls iterator.return() if the method exists. It then awaits the promise that return() gives back before continuing. Three kinds of exit trigger this call:
| Exit from the loop | `return()` called? |
|---|---|
| `break` | Yes |
| `return` from the enclosing function | Yes |
| An exception thrown in the loop body | Yes |
| Iterator returns `{ done: true }` | No, the source already finished |
| Iterator's `next()` throws or rejects | No, the source is treated as already broken |
The last row matters. If the source itself fails, the loop assumes the source already cleaned up after itself, so the loop does not call return().
Async generators get return() for free
Every async generator object already has a return() method. Calling it resumes the generator at the paused yield as though that yield were a return statement. Any enclosing finally blocks then run. So in practice, cleanup code for a generator goes in finally:
async function* openResource() {
console.log('open');
try {
yield 'a';
yield 'b';
yield 'c';
} finally {
console.log('close'); // runs on completion, break, or throw
}
}
async function main() {
for await (const item of openResource()) {
console.log(item);
if (item === 'a') break;
}
console.log('after loop');
}
main(); // open, a, close, after loopNote that close prints before after loop. The loop waits for return() to settle, so the cleanup has finished by the time the next statement runs. A finally block in an async generator can also await, for example await connection.end(), and the loop waits for that too.
The same cleanup runs when the loop body throws:
async function* openResource() {
try {
yield 'a';
yield 'b';
} finally {
console.log('close');
}
}
async function main() {
try {
for await (const item of openResource()) {
throw new Error(`bad item ${item}`);
}
} catch (err) {
console.log('Caught:', err.message);
}
}
main(); // close, then Caught: bad item aCommon mistakes
Reusing a generator after break
Once return() runs, the generator is finished for good. A second loop over the same object yields nothing:
async function* letters() {
yield 'a';
yield 'b';
yield 'c';
}
async function main() {
const gen = letters();
for await (const x of gen) {
console.log(x);
break;
}
for await (const x of gen) {
console.log('second loop:', x); // never runs
}
}
main(); // aIf you need to resume where you left off, call gen.next() manually instead of using a loop. Or wrap the generator in an object whose return() does nothing.
Cleanup placed after the loop inside the generator
Code that comes after the final yield but sits outside finally runs only when the generator completes normally. A break in the consumer skips it. Put release logic in finally so it runs on every exit path.
Expecting finally before the first next()
If you create a generator and call return() before ever calling next(), the body never started. The try block was never entered, so its finally does not run. Acquire resources inside the try, as in the examples above, so nothing gets acquired without a matching cleanup.
Exercise
An async generator opens a connection, then yields rows inside try { ... } finally { await conn.close(); }. The consumer's loop body throws on the third row. In what order do these happen: the consumer's catch block runs, conn.close() resolves?
Show answer
conn.close() resolves first. The throw in the loop body makes for await...of call the generator's return(), which runs the finally block. The loop awaits that promise, and only after cleanup finishes does the exception propagate to the consumer's catch block.
Exercise
Why does for await...of not call return() when the iterator's next() rejects?
Show answer
A rejection from next() means the source itself failed. The protocol treats a failed iterator as already closed, so it is the source's own job to clean up before rejecting. The loop just propagates the error.