Sub topic 16
Early Termination and Iterator Cleanup
A pipeline often stops before its source runs out. A take limit is reached, a for...of loop hits break, find gets a match, or a callback throws. In each of these cases the source may still hold resources such as file handles, timers, locks, or a generator with a pending finally block. This chapter explains how iterator helpers tell the source to clean up, and the timing details that catch people out.
This chapter assumes you know generator functions, try...finally, and the helpers covered earlier (map, filter, take, drop, and the consuming methods).
The Closing Protocol: `return()`
The iteration protocol has an optional method beside next(): return(). A consumer calls return() to say "I am done early." For a generator, return() resumes the paused function as though a return statement ran at the current yield. Any enclosing finally blocks therefore run.
Closing applies only to early exit. If an iterator runs to the end on its own (next() returns { done: true }), nobody calls return(), because there is nothing left to clean up.
Every iterator helper object has a return() method. Calling it closes the helper and forwards the call to the underlying iterator. In a chain like source.map(f).filter(g).take(3), closing the outer helper closes each layer in turn, down to source.
How `take` Closes Its Source
Here is the basic case:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
console.log(source().take(1).toArray());
// cleanup
// [1]toArray keeps calling next() until it gets done: true. The first pull produces 1. On the second pull, take sees its limit is used up. Instead of pulling again, it calls return() on the generator, which runs the finally block, and then reports done: true.
Gotcha: Closing Happens on the Next Pull
take does not close the source as soon as it hands out the last allowed value. It closes it the next time someone calls next(). If you pull by hand and stop, the source stays open:
function* source() {
try {
yield 1;
yield 2;
} finally {
console.log('cleanup');
}
}
const it = source().take(1);
console.log(it.next()); // { value: 1, done: false }
console.log('after first');
console.log(it.next());
// cleanup
// { value: undefined, done: true }Between the two calls the generator is suspended inside its try block. If your code walks away at that point, cleanup never runs. Consuming methods and for...of always make the extra pull or call return(), so this only matters when you drive next() yourself. In that case, finish with one more next() or call it.return() explicitly.
take(0) is the edge case: the first next() closes the source without pulling any value from it.
Other Ways a Pipeline Ends Early
`break` in a `for...of` Loop
When a for...of loop exits early through break, return, or a thrown exception, it calls return() on the iterator it was looping over. With a helper, that call travels down the chain:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
for (const x of source().map((n) => n * 10)) {
if (x >= 20) break;
console.log(x);
}
// 10
// cleanupShort-Circuiting Consumers
find, some, and every stop as soon as they know the answer, and they close the source when they do:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
console.log(source().find((n) => n === 2));
// cleanup
// 2A Callback Throws
If a callback passed to map, filter, flatMap, forEach, reduce, or any other helper throws, the helper closes the underlying iterator before the error propagates:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
try {
source()
.map((n) => {
if (n === 2) throw new Error('bad value');
return n;
})
.toArray();
} catch (e) {
console.log(e.message);
}
// cleanup
// bad valueThe opposite case works differently. If the source's own next() throws, the helpers do not call return() on it. A source that has already failed is treated as finished.
`drop` Does Not Close Anything by Itself
drop pulls and discards values. If the source runs out during the skip, the pipeline just reports done, and no closing is needed. drop closes the source only when a consumer closes it from downstream.
Summary of Closing Behavior
| How the pipeline ends | Is the source's `return()` called? |
|---|---|
| Source runs out naturally | No |
| `take` limit reached, then another `next()` | Yes |
| `take` limit reached, no further pull | No (source stays suspended) |
| `break` / `return` / `throw` inside `for...of` | Yes |
| `find`, `some`, `every` short-circuit | Yes |
| A helper callback throws | Yes |
| The source's own `next()` throws | No |
| `helper.return()` called manually | Yes |
Closing a Helper That Never Started
You can call return() on a helper before pulling anything. It still closes the underlying iterator, but with a generator source the finally block does not run, because the generator never entered its try block:
function* source() {
try {
yield 1;
} finally {
console.log('cleanup');
}
}
const gen = source();
const helper = gen.map((n) => n * 2);
console.log(helper.return()); // { value: undefined, done: true }
console.log(gen.next()); // { value: undefined, done: true }
// 'cleanup' is never loggedThis is usually correct. A generator that never started has acquired nothing yet. It does mean you should not depend on finally to undo work done before the first yield. Put resource acquisition inside the try, or after the first yield, so cleanup and acquisition stay paired.
Hand-Written Iterators and `Iterator.from`
A plain iterator object needs its own return() method to take part in cleanup. If it has none, closing it does nothing and no error is thrown. When you wrap such an object with Iterator.from, the wrapper forwards return() to it:
function openLines(lines) {
let i = 0;
return {
next() {
return i < lines.length
? { value: lines[i++], done: false }
: { value: undefined, done: true };
},
return() {
console.log('closed');
return { value: undefined, done: true };
},
};
}
const first = Iterator.from(openLines(['a', 'b', 'c'])).take(1).toArray();
console.log(first);
// closed
// ['a']When you write a resource-backed iterator, such as a cursor over a database result or a reader over a stream, give it a return() that releases the resource. Make that method safe to call more than once. It should also return an object of the form { done: true }, since callers expect an iterator result.
Exercises
Exercise
A generator has a finally block that logs 'done'. You run const it = gen().take(2); it.next(); it.next(); and nothing else. Is 'done' logged? What single call would make it log?
Show answer
No. After two pulls, take has used its limit but has not yet closed the source, and the generator is suspended inside its try block. Calling it.next() a third time makes take close the generator, and so does calling it.return(). Either one runs the finally block and logs 'done'.
Exercise
Given a generator source() with a finally block that logs 'cleanup', predict the output of console.log(source().filter((n) => n > 100).toArray()); if source() yields only 1, 2, and 3.
Show answer
The source runs out naturally, so return() is never called. The generator does reach the end of its try block, though, so finally runs on normal completion and logs 'cleanup'. Then [] is logged. The cleanup comes from normal exit here, not from closing.
Exercise
You write a custom iterator over a network cursor with next() but no return(), wrap it with Iterator.from, and call .find(...). The match is found early. Is the cursor released?
Show answer
No. find calls return() through the wrapper, but the underlying object has no return method, so nothing happens and the cursor stays open. Add a return() method that releases the cursor and returns { value: undefined, done: true }.