Skip to content

Generators & Cleanup

The Course
•
25 min study

A generator is declared with function*. Calling it returns an iterator without running its body immediately. Each next() resumes until a yield or completion. Yielded values are produced on demand; returning from the generator marks iteration done.

A for/of loop that exits early with break closes its iterator by calling return when available. A generator's finally block can therefore release a resource or record cleanup. Merely creating an iterator and abandoning it does not guarantee prompt cleanup.

Keep resource ownership explicit. A library manually pulling an iterator must decide whether to close it on failure or cancellation. Our pool owns the iterator it obtains for one invocation, closes it when unfinished, and does not promise to make the source reusable afterward.

A finally block is not a substitute for a cancellation protocol for unrelated asynchronous work. Today’s generators are synchronous. Async iterators are a different protocol and are outside this capstone's API.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
function* numbers() {
  try {
    yield 1;
    yield 2;
  } finally {
    console.log("closed");
  }
}

for (const value of numbers()) {
  console.log(value);
  break;
}
Check your prediction
Text
1
closed

Creation, advancement and closing are separate events

Calling a generator function creates an iterator; it does not run the body to completion. Each next resumes the suspended body until the next yield or return. Side effects therefore happen when a consumer requests values, not when the generator object is created.

A consumer that owns a resource-bearing iterator must also understand early closure. A for-of break requests cleanup, while simply retaining the iterator after one next leaves it suspended. Generator validation inside the body is likewise deferred until advancement.

Creation, advancement and closing are separate events: trace JavaScript
function* values() {
  console.log("entered");
  yield 1;
  console.log("resumed");
  yield 2;
}

const cursor = values();

console.log("created");
console.log(cursor.next().value);
console.log(cursor.next().value);
Check your prediction
Text
created
entered
1
resumed
2

The first body log is delayed until next. After the first yield, execution resumes below that yield on the following request.

Creation, advancement and closing are separate events: contrast JavaScript
function* source() {
  try {
    yield "a";
    yield "b";
  } finally {
    console.log("released");
  }
}

const cursor = source();

console.log(cursor.next().value);
cursor.return();
console.log(cursor.next().done);
Check your prediction
Text
a
released
true

Return closes the unfinished generator and executes finally. It does not consume b as another ordinary result. A later next reports completion.

Try the rule on new inputs

Compare normal exhaustion, for-of break and explicit return. Add a validation throw at the start of the body and identify which operation observes it: generator creation or the first next call.

Debug a plausible mistake

Exercise

Repair yielded batch ownership

Each yielded batch must remain stable after later iteration. Print 2,2 for the retained pairs. Add a fifth value and expect a final batch of length 1. Preserve the source.

Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspace JavaScript
function* pairs(values) {
  let batch = [];

  for (const value of values) {
    batch.push(value);
    if (batch.length === 2) {
      yield batch;
      batch.length = 0;
    }
  }
  if (batch.length > 0) {
    yield batch;
  }
}

const result = [...pairs([1, 2, 3, 4])];

console.log(result.map(batch => batch.length).join(","));
Hint 1: the idea

Yielding an array exposes that object; clearing it later changes the value the caller retained.

Hint 2: a first step

Use a fresh container for the next batch rather than emptying the yielded one.

Show one solution
JavaScript
function* pairs(values) {
  let batch = [];

  for (const value of values) {
    batch.push(value);
    if (batch.length === 2) {
      yield batch;
      batch = [];
    }
  }
  if (batch.length > 0) {
    yield batch;
  }
}

const result = [...pairs([1, 2, 3, 4])];

console.log(result.map(batch => batch.length).join(","));
Text
2,2

The original printed 0,0. yield batch hands the caller the array itself, not a copy, so batch.length = 0 emptied the pair the caller had just stored; by the end both stored entries were the same emptied array. batch = [] leaves the yielded array alone and gives the next pair a new one. Running pairs([1, 2, 3, 4, 5]) prints 2,2,1, and only the repaired version keeps the final short batch separate from the earlier ones.

Trace the contract before building

Creating a generator object does not run its body immediately. Validation inside that body therefore occurs when consumption starts. State the timing if callers may construct a pipeline now and consume it much later.

Yield also exposes the actual value object to the caller. Reusing and clearing a yielded array can corrupt previously retained batches; allocate another container when independent batches are promised. For cleanup, distinguish a consumer that exits through the iteration protocol from one that simply abandons a reference. finally can participate in closure, but it cannot make every unrelated async operation cancel itself.

Your turn

Exercise

Cleanup when the loop body throws

Write readLines(lines, log), a generator that pushes "open" to log when its body starts, yields each line, and in finally pushes close after N, where N counts lines the consumer finished with (the yield that was interrupted does not count). Then check three consumers: one that only creates the generator, a for...of whose body throws on "bad", and one that calls return() before ever calling next(). Predict each line before running. Print:

Text
created only: (nothing)
thrown: open, close after 2, bad line
return before next: (nothing)
Your workspace JavaScript
function* readLines(lines, log) {
  // push "open", yield each line, and push `close after ${sent}` in finally
}

const lines = ["a", "b", "bad", "c"];

const thrown = [];
try {
  for (const line of readLines(lines, thrown)) {
    if (line === "bad") throw new Error("bad line");
  }
} catch (error) {
  thrown.push(error.message);
}
console.log(`thrown: ${thrown.join(", ")}`);
Hint 1: the idea

A throw in the loop body leaves for...of early, just like break, so it closes the iterator. The question is what finally can see at that moment, and whether a generator that never started has a try block to run at all.

Hint 2: a first step

Put log.push("open") and let sent = 0 before the try, and increment sent on the line after yield line. Run the thrown case first: if it prints close after 3, the counter is above the yield.

Show one solution
JavaScript
function* readLines(lines, log) {
  log.push("open");
  let sent = 0;
  try {
    for (const line of lines) {
      yield line;
      sent += 1;
    }
  } finally {
    log.push(`close after ${sent}`);
  }
}

const lines = ["a", "b", "bad", "c"];

const unused = [];
readLines(lines, unused);
console.log(`created only: ${unused.join(", ") || "(nothing)"}`);

const thrown = [];
try {
  for (const line of readLines(lines, thrown)) {
    if (line === "bad") throw new Error(`bad line`);
  }
} catch (error) {
  thrown.push(error.message);
}
console.log(`thrown: ${thrown.join(", ")}`);

const neverStarted = [];
readLines(lines, neverStarted).return();
console.log(`return before next: ${neverStarted.join(", ") || "(nothing)"}`);
Text
created only: (nothing)
thrown: open, close after 2, bad line
return before next: (nothing)

Creating a generator runs none of its body, so nothing is opened and nothing needs closing. When the body throws on "bad", for...of calls return() before the error reaches catch: the generator resumes at the suspended yield as if it returned there, skips sent += 1, and runs finally with 2. That is why close after 2 is logged before bad line. Calling return() before the first next() closes a generator that never entered its try, so finally does not run and open is never logged: cleanup code only guards a resource the body actually acquired.

Change it and test it

Compare break with calling next once and retaining the iterator. Call return explicitly on that retained iterator and observe cleanup. Explain why a library cannot just forget an unfinished resource-owning iterator after a callback throws.

Was this article helpful?

Your response is saved on this device.