Sub topic 6
Breaking Out Early and Cleaning Up
A loop does not always run to the end. You might find the item you were looking for, hit a limit, or throw an error. When the data comes from a file, a network connection, or a database cursor, stopping early leaves a question open: who closes the resource? This chapter shows how for await...of answers that question by calling the iterator's return() method, and how async generators turn that call into a finally block that runs reliably.
This chapter assumes you know Promises and async/await, the async iteration protocol (Symbol.asyncIterator, next() returning a Promise of { value, done }), for await...of, and writing async generators with async function*.
What return() Is For
The async iteration protocol requires only next(). It also defines two optional methods: return() and throw(). The consumer calls return(value) to tell the producer that no more values will be requested. The producer can then release whatever it holds and should resolve to { value, done: true }.
You rarely call return() yourself. for await...of calls it for you when the loop exits abruptly, meaning any exit other than the iterator reporting done: true.
A First Example: break Triggers finally
An async generator has return() built in. When it is called while the generator is paused at a yield, the generator resumes as if that yield were a return statement. Any enclosing finally blocks run on the way out.
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;
}
}
main(); // open, a, closeThe break makes the loop call return() on the generator. The generator is paused at yield 'a', so it resumes there with a return completion. The values 'b' and 'c' are never produced, and the finally block logs close.
Which Exits Call return()
The rule is simple. If the loop leaves because the consumer decided to stop, return() is called. If it leaves because the producer finished or failed, return() is not called.
| How the loop ends | `return()` called? | Why |
|---|---|---|
| Iterator yields `done: true` | No | The producer already finished |
| `break` in the body | Yes | Consumer stopped early |
| `return` from the enclosing function | Yes | Consumer stopped early |
| `throw` in the body (or a rejected `await` in the body) | Yes | Consumer stopped early |
| `continue outerLabel` or `break outerLabel` that leaves the loop | Yes | Consumer stopped early |
| `next()` rejects, or the generator throws | No | The producer failed and is assumed to have cleaned up |
The last row matters most when you write iterators by hand. In a generator, a throw inside the try still passes through its own finally, so cleanup happens anyway. In a hand-built iterator, a rejected next() means return() will not be called. Your next() must release resources on its own error path.
Cleanup Can Be Async, and the Loop Waits for It
for await...of awaits the Promise returned by return() before running the code after the loop. You can therefore await inside finally, for example to flush a buffer or close a socket, and be sure it is done before you move on.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* connection() {
console.log('connect');
try {
for (let i = 1; ; i++) {
await sleep(50);
yield i;
}
} finally {
await sleep(100); // simulate an async close
console.log('disconnected');
}
}
async function main() {
for await (const n of connection()) {
console.log('got', n);
if (n === 2) break;
}
console.log('after loop');
}
main(); // connect, got 1, got 2, disconnected, after loopThe generator here is infinite. The only way out is the consumer stopping, so finally is its only chance to clean up. Because the loop awaits return(), after loop prints only after disconnected.
Throwing from the Loop Body
When the body throws, the loop calls return(), waits for it, and only then lets the error propagate. Cleanup therefore runs before your catch block.
async function* openResource() {
console.log('open');
try {
yield 1;
yield 2;
} finally {
console.log('close');
}
}
async function main() {
try {
for await (const n of openResource()) {
console.log(n);
throw new Error('consumer failed');
}
} catch (err) {
console.log('caught:', err.message);
}
}
main(); // open, 1, close, caught: consumer failedIf cleanup itself fails, which error wins depends on how the loop was leaving:
- On
breakorreturn, an error fromreturn()(for example, afinallyblock that throws) propagates out of the loop. - On
throw, the original error from the body wins, and the error fromreturn()is discarded.
The second rule keeps the root cause visible, but it also means a failed cleanup can go unnoticed. If cleanup failures matter, catch and log them inside the finally block.
async function* guarded() {
try {
yield 1;
} finally {
try {
await closeSomething();
} catch (cleanupErr) {
console.error('cleanup failed:', cleanupErr.message);
}
}
}
async function closeSomething() {
throw new Error('socket already closed');
}
async function main() {
for await (const n of guarded()) {
break;
}
console.log('done');
}
main(); // cleanup failed: socket already closed, doneGotchas
A generator that never started skips its finally
If you call return() on a generator before its first next(), the body never runs. Nothing inside it executes, including finally.
async function* openResource() {
console.log('open');
try {
yield 'a';
} finally {
console.log('close');
}
}
async function main() {
const gen = openResource();
const result = await gen.return('stopped');
console.log(result); // { value: 'stopped', done: true }
// Neither 'open' nor 'close' was logged
}
main();This is usually harmless, because nothing was opened. It turns into a bug when the resource is acquired outside the generator and passed in, expecting the generator's finally to close it. Acquire resources inside the generator, after the try begins or just before it, so that acquisition and release live in the same body.
Code before the try is not protected
In openResource, console.log('open') runs before try. If the real acquisition step fails there, no cleanup is needed. But if you acquire two resources and the second acquisition throws, the first one leaks unless it is already inside a try. Nest one try/finally per resource, or acquire inside a single try and check what needs releasing in finally.
Yielding inside finally stalls cleanup
A yield inside finally pauses the generator in the middle of cleanup. for await...of calls return() once, receives the yielded value as { value, done: false }, ignores it, and moves on. The rest of the finally block never runs.
async function* badCleanup() {
try {
yield 1;
yield 2;
} finally {
yield 'cleanup-step'; // pauses here when return() is called
console.log('closed'); // never logged after a break
}
}
async function main() {
for await (const n of badCleanup()) {
break;
}
console.log('after loop');
}
main(); // after loopKeep finally blocks free of yield. Use await for async cleanup.
A broken-out generator is finished for good
A generator object is its own iterator, and return() closes it permanently. Looping over the same object again produces nothing.
async function* numbers() {
yield 1;
yield 2;
yield 3;
}
async function main() {
const gen = numbers();
for await (const n of gen) {
console.log('first loop', n);
break;
}
for await (const n of gen) {
console.log('second loop', n); // never runs
}
}
main(); // first loop 1To resume later, you must avoid for await...of's automatic close. One option is to wrap the generator in an iterable whose return() does nothing. A clearer option is to call gen.next() by hand. Iterables that create a fresh iterator on every [Symbol.asyncIterator]() call, such as the hand-built objects in the next chapter, do not have this problem.
Manual next() calls get no automatic cleanup
Only language constructs call return() for you. If you drive an iterator with next() directly and stop early, the producer's finally will not run unless you call return() yourself. Garbage collection does not run it either. Wrap manual consumption in try/finally:
async function* openResource() {
console.log('open');
try {
yield 'a';
yield 'b';
} finally {
console.log('close');
}
}
async function firstValue(iterable) {
const it = iterable[Symbol.asyncIterator]();
try {
const { value, done } = await it.next();
return done ? undefined : value;
} finally {
await it.return?.(); // optional: hand-built iterators may lack return()
}
}
firstValue(openResource()).then((v) => console.log('first:', v));
// open, close, first: aThe optional call it.return?.() matters. return() is optional in the protocol, and for await...of also skips it quietly when it is missing.
return() must resolve to an object
When the loop exits by break or return, it checks that return() resolves to an object. A hand-written return() that resolves to undefined causes a TypeError at the loop. Always resolve to { value: undefined, done: true } or similar.
When to Rely on This
Use try/finally in an async generator whenever it holds something that must be released: file handles, sockets, locks, timers, subscriptions, or database cursors. It is the only place that runs on every exit path: normal completion, a consumer's break or throw, and the generator's own errors. Hand-built iterators need two cleanup paths, one in return() for consumer exits and one in next() for their own failures. Later chapters rely on this behaviour: Node.js streams destroy themselves when a loop breaks, and pipeline stages such as take() stop upstream fetching by returning early.
Exercise
An async generator opens a database cursor inside a try block and closes it in finally with await cursor.close(). A for await...of loop over it hits break on the third row. List the order of events from the break to the first statement after the loop, and say whether the statement after the loop can observe an open cursor.
Show answer
The break makes the loop call return() on the generator. The generator resumes at its paused yield as a return completion, enters finally, and awaits cursor.close(). When finally completes, the generator resolves return() with { value: undefined, done: true }. The loop awaits that Promise, and only then does the statement after the loop run. The cursor is already closed at that point, so code after the loop cannot observe it open.
Exercise
A hand-built async iterator opens a socket on its first next() call and closes it in return(). Its next() rejects when the socket emits an error. Why can the socket leak, and how do you fix it?
Show answer
for await...of does not call return() when next() rejects, because it treats a failing producer as responsible for its own cleanup. The socket stays open. The fix is to close the socket inside next() before rejecting, for example with a try/catch that closes it and rethrows. Or rewrite the iterator as an async generator with try/finally, which covers both exit paths.
Exercise
The loop body throws Error('A'), and the generator's finally block throws Error('B') while cleaning up. Which error reaches the catch around the loop? What changes if the body uses break instead of throw?
Show answer
With throw, the catch receives Error('A'). The original error wins, and the error from return() is discarded. With break, there is no pending error, so Error('B') from return() propagates and the catch receives it.
Exercise
Why does calling gen.return() on a freshly created async generator object not run its finally block, and what design rule avoids problems from this?
Show answer
The generator body has not started, so no try block has been entered. return() completes the generator immediately without running any of its code. Acquire resources inside the generator body, inside or right before the try whose finally releases them, so that a generator that never runs also never acquires anything.