Skip to content

Lesson 8 of 9 · 24m

Generators as Resumable Functions

How `yield` suspends execution state, how values flow both directions, and where generators beat callbacks or ad-hoc state machines.

Generators are often introduced as a concise way to write iterators, which undersells them. A generator is a resumable function: it can suspend at yield, preserve its local variables, and resume later. The runtime is not snapshotting the whole process; the generator object owns its execution state.

yield is a boundary, not a return

function* dialog() {
  const name = yield "What is your name?";
  const confirmed = yield `Confirm ${name}?`;
  return confirmed ? `welcome ${name}` : "cancelled";
}

const flow = dialog();
flow.next();        // { value: "What is your name?", done: false }
flow.next("Ada");   // resumes; name becomes "Ada"
flow.next(true);    // { value: "welcome Ada", done: true }

The first next() starts execution and the argument is ignored because no yield is waiting yet. Later arguments become the result of the suspended yield expression. That bidirectional channel is why generators can model interactive workflows and coroutine-like control flow.

Errors can be thrown back inside

function* worker() {
  try {
    yield "ready";
    yield "working";
  } catch (error) {
    yield `recovered: ${error.message}`;
  } finally {
    cleanup();
  }
}

generator.throw(error) resumes at the suspended yield as if that expression threw. generator.return(value) acts as an early completion and runs finally blocks. These are not obscure extras; they are the resource-correctness mechanisms behind cancellation.

Generators compose without arrays

function* lines(text) {
  yield* text.split("\n");
}

function* nonEmpty(source) {
  for (const line of source) {
    if (line.trim()) yield line;
  }
}

const result = nonEmpty(lines(logText));

yield* delegates to another iterable, forwarding values in both directions. Composed generators remain lazy: the split above still materializes lines, but further transformations do not build intermediate collections unless you choose to collect them.

Where they shine in real systems

  • Paging APIs: yield items while hiding page tokens and rate-limit backoff.
  • State machines: suspend at the exact point user input is needed.
  • Test fixtures: deterministic infinite sequences without preallocating data.
  • Tree traversal: recursive yield* exposes nodes in order without callbacks.

Async generators add await inside the producer and for await...of on the consumer. They are ideal for streams that are naturally pull-based, such as paginated scans.

Field notes

  • A generator body does not execute when the generator function is called. It starts on the first next().
  • Once done: true, the generator is finished; you cannot rewind it.
  • return() during a finally that itself yields is subtle — keep cleanup small and synchronous where possible.
  • Generators are poor random-access APIs. If callers need indexes and repeated scans, materialize an array deliberately.

Was this lesson helpful?

Sign in to rate