Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Generator return() and finally cleanup in JavaScript

3 return() on a generator runs its finally

hard

Write a generator that acquires something in a try and releases it in a finally. Prove that return() releases it, that breaking out of a for...of releases it too, and that simply walking away from a half-read generator does not.

Stuck? Three hints, smallest first
  1. 1. gen.return(v) resumes the generator as though a return v had appeared at the paused yield.
  2. 2. for...of calls return() on the iterator when the loop exits early, which includes break, throw and an early return.
  3. 3. Nothing calls it for you if you just stop touching the generator. There is no finaliser.

The answer

function* connection(log) {
  log.push('open');
  try {
    yield 'row 1';
    yield 'row 2';
    yield 'row 3';
  } finally {
    log.push('close');            // runs on normal end, on return(), on throw()
  }
}

const log = [];
const rows = connection(log);
const read = [rows.next().value, rows.next().value];
const ended = rows.return('stopped early');
const afterwards = rows.next();

// for...of does the same thing for you when you break.
const loopLog = [];
const loopRead = [];
for (const row of connection(loopLog)) {
  loopRead.push(row);
  if (loopRead.length === 1) break;
}

// And nothing at all happens if you simply stop reading.
const abandonedLog = [];
const abandoned = connection(abandonedLog);
abandoned.next();

console.log('read      :', read);
console.log('return()  :', JSON.stringify(ended));
console.log('log       :', log);
console.log('after break:', loopLog, loopRead);
console.log('abandoned :', abandonedLog, '<- never closed');

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('two rows were read', read, ['row 1', 'row 2']);
test('return() reports done, with the value you gave it', ended, { value: 'stopped early', done: true });
test('and the finally block ran', log, ['open', 'close']);
test('nothing more comes out afterwards', [afterwards.done, afterwards.value === undefined], [true, true]);
test('breaking out of for...of calls return() for you', loopLog, ['open', 'close']);
test('so cleanup happens on an early exit too', loopRead, ['row 1']);
test('but a generator you simply abandon never cleans up', abandonedLog, ['open']);
test('the finally runs at most once', connection(log) && log.filter((l) => l === 'close').length, 1);

This is the mechanism that makes a generator safe to hold a resource. return() is not "stop it", it is "resume it as if a return statement were sitting at the paused yield" — so the finally runs, exactly as it would on a real early return.

for...of calling return() on early exit is specified behaviour (the IteratorClose step), and it is why break out of a loop over a database cursor closes the cursor. It also fires for throw and for a return out of the enclosing function.

The last two assertions are the boundary. There is no destructor in JavaScript. A generator that is paused inside a try and then dropped on the floor has its finally skipped for ever, and the file handle or connection leaks. If a generator owns something, the consumer has to finish it, break out of a loop over it, or call return() — and try { ... } finally { gen.return(); } around the consumer is how you guarantee that.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.