Sub topic 13
Cleaning Up with try...finally in Generators
This chapter assumes you know how generators pause at yield, how return() and throw() resume them from outside, and how for...of calls an iterator's return() when you leave a loop early. Here you put those pieces together. You will see how a generator releases a resource reliably, where that guarantee holds, and where it breaks.
The Pattern: Acquire, try, yield, finally
A generator that owns a resource, such as a file handle, a database cursor, or a lock, should acquire it, open a try block, yield from inside the try, and release the resource in finally. When the consumer stops early, the engine calls the generator's return(). That method resumes the paused generator as if a return statement stood where the yield was, so every enclosing finally block runs on the way out.
function openResource(name) {
console.log(`open ${name}`);
return {
read(i) { return `${name}:${i}`; },
close() { console.log(`close ${name}`); }
};
}
function* readRecords(name, count) {
const res = openResource(name);
try {
for (let i = 0; i < count; i++) {
yield res.read(i);
}
} finally {
res.close();
}
}
for (const rec of readRecords('db', 5)) {
console.log(rec);
if (rec === 'db:1') break;
}
// open db
// db:0
// db:1
// close dbThe consumer never had to know that a resource existed. The break triggered return(), return() ran the finally block, and the handle closed. If the loop had run all five records, the finally block would have run on normal completion instead.
Which Exits Run finally
The guarantee depends on how the consumer leaves. The next example labels each case.
function* tracked(label) {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log(`finally: ${label}`);
}
}
// 1. Run to completion
for (const x of tracked('complete')) {}
// 2. break out of the loop
for (const x of tracked('break')) break;
// 3. An error thrown in the loop body
try {
for (const x of tracked('throw')) throw new Error('boom');
} catch (e) {}
// 4. Destructuring takes one value and closes the iterator
const [a] = tracked('destructure');
// 5. Manual next(), then the generator is abandoned
const g = tracked('abandoned');
g.next();
// 6. return() before the first next()
const fresh = tracked('never started');
console.log(fresh.return('bye'));
// Output:
// finally: complete
// finally: break
// finally: throw
// finally: destructure
// { value: 'bye', done: true }| How iteration ends | Is `return()` or `throw()` called? | Does `finally` run? |
|---|---|---|
| Generator body finishes | No | Yes, normally |
| `break`, `return`, or `continue label` out of `for...of` | `return()` | Yes |
| Exception in the loop body | `return()` | Yes |
| Destructuring stops before the end | `return()` | Yes |
| Consumer calls `throw(err)` while paused in `try` | `throw()` | Yes, after any `catch` |
| Consumer calls `next()` manually and walks away | No | No |
| `return()` before the first `next()` | `return()` | No, the body never started |
The last two rows are the gotchas. JavaScript has no garbage-collection hook for generators. A suspended generator that nobody closes keeps its finally pending until it is collected, and then the block never runs. If you drive a generator by hand, close it yourself with return(), preferably from your own finally block.
A generator that has not started has not entered its try yet, so it has no cleanup to do. Calling return() on it moves it straight to completed. That is correct behavior, but it means code placed before the try never runs either.
catch Versus finally
return() is not an error, so it skips catch blocks and runs only finally. throw() raises an exception at the yield, so catch runs first and finally runs after it.
function* guarded() {
try {
yield 'working';
} catch (err) {
console.log('catch:', err.message);
} finally {
console.log('finally');
}
}
const g1 = guarded();
g1.next();
g1.return('stop');
// finally
const g2 = guarded();
g2.next();
g2.throw(new Error('bad'));
// catch: bad
// finallyPut release logic in finally, not in catch. A catch-only cleanup leaks on every break.
Nested finally Blocks and yield*
When try blocks are nested, their finally blocks run from the inside out. Delegation follows the same order. Calling return() on an outer generator that is paused inside yield* forwards the call to the inner iterator first. The inner generator's finally runs, then the outer one's.
function* inner() {
try {
yield 'inner value';
} finally {
console.log('inner cleanup');
}
}
function* outer() {
try {
yield* inner();
} finally {
console.log('outer cleanup');
}
}
for (const v of outer()) {
console.log(v);
break;
}
// inner value
// inner cleanup
// outer cleanupThis is why a pipeline of generator stages, each with its own try...finally, cleans up correctly when the final consumer stops. Each stage's for...of loop closes its source as it unwinds.
Mistakes Inside finally
Yielding in finally
A finally block may contain yield, but doing so changes how return() behaves. The generator pauses again and return() reports done: false.
function* stubborn() {
try {
yield 1;
} finally {
yield 'cleanup step';
console.log('really done');
}
}
const s = stubborn();
s.next();
console.log(s.return('x')); // { value: 'cleanup step', done: false }
console.log(s.next()); // logs 'really done', then { value: 'x', done: true }for...of calls return() only once and ignores the result. After a break, the rest of this finally block never runs. Keep finally blocks free of yield.
Returning from finally
A return statement in finally replaces whatever completion was in progress. That includes the value passed to return(), and it also includes exceptions, which disappear without a trace.
function* override() {
try {
yield 1;
throw new Error('lost');
} finally {
return 'from finally';
}
}
const o = override();
o.next();
console.log(o.next()); // { value: 'from finally', done: true }, and the error is goneThrowing from finally
If the cleanup itself throws, the error propagates to whoever called return(). With for...of, the error surfaces at the break statement. When cleanup can fail and the failure is not important, wrap it in its own try...catch inside finally so that one bad close does not hide the original result.
Closing Generators You Drive by Hand
When you call next() yourself instead of using for...of, you take on the job for...of would have done:
function* numbers() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('numbers closed');
}
}
const it = numbers();
try {
const first = it.next();
const second = it.next();
console.log(first.value + second.value); // 3
} finally {
it.return(); // logs 'numbers closed'
}Calling return() on a generator that has already completed is harmless. It simply returns { value: undefined, done: true }, so you can call it unconditionally.
Exercise
A generator acquires a lock before its try block and releases it in finally. A caller writes const it = gen(); it.return(); without ever calling next(). Is the lock acquired, and is it released?
Show answer
Neither happens. return() on a generator that has not started moves it directly to the completed state, so no part of the body runs. The acquire code before the try never executes, and the finally block never executes either. That is consistent, because nothing was acquired.
Exercise
What does this log? function* g() { try { yield 'a'; yield 'b'; } catch (e) { console.log('caught'); } finally { console.log('done'); } } followed by const [x] = g(); console.log(x);
Show answer
It logs "done" and then "a". Destructuring takes one value and then calls return() on the iterator. return() runs the finally block but skips catch, so "caught" is never printed. The console.log(x) call comes after destructuring finishes, so "a" prints last.
Exercise
Why does a break out of for...of fail to finish cleanup when the generator's finally block contains a yield?
Show answer
break calls return() once. The finally block starts and then pauses at its yield, so return() comes back with done: false. for...of ignores that result and never calls next() again, which leaves the code after the yield in finally unexecuted.