Generator finally Runs On return And throw

A finally block inside a generator executes when return() or throw() terminates it — the cleanup hook fires on every shutdown path, not just next().

JavascriptResilience

Code

javascriptsnippet
19 lines
function* ticker() {
  let tick = 0;
  try {
    while (true) {
      yield ++tick;
    }
  } finally {
    // finally runs on return() and throw() - not on plain next()
    console.log('ticker cleanup after', tick, 'ticks');
  }
}

const t = ticker();
console.log('tick 1:', t.next().value);
console.log('tick 2:', t.next().value);

// return() stops the generator immediately and carries the value out
console.log('stopped with:', t.return('done'));
console.log('done flag:', t.next().done);

What the code does

while (true) is the loop that carries the per-item work.

Points of care

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

Look for the ticker cleanup after, tick 1:, tick 2: prefixes as the file executes; they connect every printed line to the step behind it.

Key statements worth quoting

yield ++tick;

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language.