Sub topic 13
Cleaning Up with try...finally in Generators
This chapter assumes you know how for...of calls an iterator's return() method on early exit, and how next(), throw(), and return() drive a generator from outside.
A hand-written iterator releases resources in its own return() method. A generator handles this for you. When a generator's return() is called while it is paused at a yield, the generator resumes as if that yield were a return statement. Any enclosing finally blocks then run before it finishes. Wrapping the generator body in try...finally therefore gives you one place to put cleanup code.
The basic pattern
function* lines() {
console.log('open');
try {
yield 'line 1';
yield 'line 2';
} finally {
console.log('close');
}
}
for (const line of lines()) {
console.log(line);
break;
}
// open
// line 1
// closeThe break makes for...of call return() on the generator. The generator was paused at yield 'line 1', so it resumes there in "returning" mode, runs the finally block, and completes.
The paths that reach finally
The finally block runs on every exit path that a consumer can trigger:
| How the generator ends | Does `finally` run? |
|---|---|
| The body runs to the end (the consumer exhausts it) | Yes |
| `break`, `return`, or an exception in a `for...of` body | Yes, through `return()` |
| A manual `gen.return(value)` call | Yes |
| A manual `gen.throw(err)` call | Yes, and then the error propagates |
| `next()` was never called, then `return()` is called | No, because the body never started |
| The generator is paused and then abandoned | No |
function* lines() {
console.log('open');
try {
yield 'line 1';
yield 'line 2';
} finally {
console.log('close');
}
}
const g = lines();
g.next(); // logs 'open'
console.log(g.return('stopped')); // logs 'close', then { value: 'stopped', done: true }
try {
for (const line of lines()) {
throw new Error('boom');
}
} catch (e) {
console.log(e.message);
}
// open
// close
// boomThe abandoned-generator gap
JavaScript has no hook that fires when an object is garbage collected. Suppose you call next() by hand a few times and then drop the generator. The generator stays paused forever, and its finally block never runs. Consume generators with for...of, spread, or destructuring, because these always close the iterator. If you must call next() manually, call return() yourself inside your own finally.
Exercise
A generator logs 'open', then yields three values inside try...finally, and its finally block logs 'close'. You run const [a] = gen();. What gets logged, and why?
Show answer
It logs 'open' and then 'close'. Array destructuring takes only the first value. It then calls the iterator's return() because the iterator is not exhausted. The generator resumes at its first yield in returning mode and runs the finally block.
Exercise
You call const g = gen(); g.next(); and then let g go out of scope. Does the finally block run? How would you make sure it does?
Show answer
No. The generator stays paused at its yield, and garbage collection does not resume it. Wrap your manual use in try { ... } finally { g.return(); }, or consume the generator with for...of, which calls return() for you.