Sub topic 16
Early Termination and Iterator Cleanup
This chapter assumes you know generator functions, including try...finally inside them, and that you have used take and the consuming methods from earlier chapters.
Many iterators hold resources: a file handle, a database cursor, a network stream, or a lock. If a pipeline stops reading early, those resources must still be released. Iterator helpers handle this through the return() method of the iteration protocol.
How closing works
An iterator can have an optional return() method. Calling it tells the iterator that no more values will be requested. For a generator, return() resumes it as if a return statement ran at the paused yield. Any finally blocks then run.
Helpers call return() on the underlying iterator whenever they stop before it is exhausted:
| Situation | Who closes the source |
|---|---|
| `take(n)` has yielded `n` values and is pulled again | `take` |
| `find`, `some`, or `every` gets its answer early | the consuming method |
| A callback passed to `map`, `filter`, and so on throws | the helper |
| You call `return()` on a helper | the helper, which forwards the call |
| `break` inside `for...of` over a helper | the loop, through the helper |
take closes the generator
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
console.log(source().take(1).toArray());
// cleanup
// [1]toArray pulls once and gets 1. It pulls again, and take sees that its limit is used up. Instead of asking the generator for another value, take calls the generator's return(), which runs the finally block. Only after that does toArray return.
Early answers from consuming methods
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
console.log(source().some((x) => x === 2));
// cleanup
// truesome stops at 2, closes the source, and never asks for 3.
Closing a helper by hand
function* source() {
try {
yield 1;
yield 2;
} finally {
console.log('cleanup');
}
}
const doubled = source().map((x) => x * 2);
console.log(doubled.next().value); // 2
doubled.return(); // cleanup
console.log(doubled.next().done); // trueCommon errors
- Abandoning a half-read iterator. If you call
next()a few times and then drop the reference, nothing callsreturn(). The resource stays open until garbage collection, and garbage collection never runsfinally. Close the iterator explicitly, or lettake,find, orfor...ofwithbreakclose it for you. - Expecting cleanup from exhausted sources. A source that runs to the end finishes normally.
finallystill runs, butreturn()is not called.
Exercise
In source().filter((x) => { if (x === 2) throw new Error('bad'); return true; }).toArray(), with source from the first example, does "cleanup" print before the error reaches your code?
Show answer
Yes. When the filter callback throws, the helper closes the underlying generator by calling its return() method. The finally block logs "cleanup", and then the error propagates out of toArray.