JavaScriptFundamental (ES6), part 2
Cancel an async generator in JavaScript
15 Cancel an async generator
hardWrite an infinite async generator that "subscribes" in a try and unsubscribes in a finally. Show that break out of for await unsubscribes, that return() does too, and that abandoning it does not.
Stuck? Three hints, smallest first
- 1. The same IteratorClose rule applies: leaving a
for awaitearly callsreturn()on the async iterator. - 2.
await gen.return(v)resolves to a done result once thefinallyhas finished. - 3. A generator you stop awaiting is simply parked for ever. Nothing collects it.
let cleanups = 0;
async function* subscription(log) {
log.push('subscribe');
try {
let n = 1;
while (true) {
await Promise.resolve(); // pretend a message arrived
yield 'event ' + n++;
}
} finally {
cleanups++;
log.push('unsubscribe');
}
}
const breakLog = [];
const got = [];
for await (const event of subscription(breakLog)) {
got.push(event);
if (got.length === 2) break;
}
const returnLog = [];
const s = subscription(returnLog);
await s.next();
const ended = await s.return('cancelled');
const afterwards = await s.next();
const abandonedLog = [];
const abandoned = subscription(abandonedLog);
await abandoned.next();
console.log('events :', got);
console.log('break :', breakLog);
console.log('return() :', JSON.stringify(ended), returnLog);
console.log('abandoned :', abandonedLog, '<- still subscribed, for ever');
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two events arrived', got, ['event 1', 'event 2']);
test('breaking out ran the finally block', breakLog, ['subscribe', 'unsubscribe']);
test('return() resolves to a done result carrying your value', ended, { value: 'cancelled', done: true });
test('and it runs the finally too', returnLog, ['subscribe', 'unsubscribe']);
test('nothing comes out after cancelling', [afterwards.done, afterwards.value === undefined], [true, true]);
test('a generator you simply stop reading never cleans up', abandonedLog, ['subscribe']);
test('so exactly two of the three subscriptions were closed', cleanups, 2);
An infinite async generator is the natural shape for a subscription, and the finally is the unsubscribe. What makes it work is that the language calls return() for you on early exit, so the ordinary break a reader would write is also the cleanup.
cleanups === 2 is the honest accounting. Three subscriptions were opened; two were closed. The abandoned one is not leaked in the memory sense — it will be collected once nothing references it — but its finally never runs, so whatever it was holding on the other side stays held. There is no finaliser to save you.
The pattern that makes this safe in real code: whoever creates the generator owns closing it, and does so in its own finally. const it = subscription(); try { for await (...) {} } finally { await it.return(); } is verbose and correct. Calling return() twice is harmless, which is what makes the belt-and-braces version viable.