Skip to content
jshacks.dev
Functions

Generator Use Cases Beyond Iteration

Five uses of JavaScript generators beyond looping: two-way communication, state machines, id sequences, chunked work and async flow with a runner. Node.js 24.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, npm, Vite and Node.js logos.

Generators are usually introduced as a way to write custom iterators, and that is the use case with the shortest code and the least surprise. Their stranger ability, pausing in the middle of a function and resuming later with a value passed back in, is what makes them more than iteration sugar. A generator is a function you can suspend, inspect and continue, and that unlocks designs that are awkward without it: a conversation between a function and its caller, a state machine written as straight-line code, a long task cut into slices that let other work through, and the control flow that async and await are built on. This post shows five such uses on Node.js 24, each with working code and its output, and says when a plain function would be the better choice. For the basics of the lazy iteration use, see building an infinite sequence generator.

The mechanism that makes the rest possible

yield does two things. It hands a value out to the caller, and the value of the yield expression is whatever the caller passes into the next next(...) call.

JavaScript
function* conversation() {
  const name = yield "What is your name?";
  const age = yield `Hello ${name}, how old are you?`;

  return `${name} is ${age}`;
}

const talk = conversation();

console.log(talk.next().value);
console.log(talk.next("Ada").value);
console.log(talk.next(36));
Text
What is your name?
Hello Ada, how old are you?
{ value: 'Ada is 36', done: true }

The first next() runs the function to the first yield, whose argument is the question. The value passed to the second next("Ada") becomes the result of the first yield, so name is "Ada". The function keeps its local variables between pauses, which is the entire point: state lives in the function's own locals instead of in an object you maintain by hand. The first next() call cannot carry a value, since no yield is waiting to receive it.

1. Two-way communication: a running average

A generator can hold state and respond to each value sent in.

JavaScript
function* runningAverage() {
  let sum = 0;
  let count = 0;
  let average = null;

  while (true) {
    const value = yield average;
    sum += value;
    count += 1;
    average = sum / count;
  }
}

const avg = runningAverage();

avg.next();

console.log(avg.next(10).value);
console.log(avg.next(20).value);
console.log(avg.next(60).value);
Text
10
15
30

The caller pushes numbers in and reads the average out. The first bare avg.next() starts the generator and runs it to the first yield, which is called priming. Compare this with the object version, which needs a class, a constructor and fields. The generator is shorter, and the state is private by construction. For simple cases a closure does the same, so the generator earns its place when the logic has several stages, as in the next example.

2. A state machine as straight-line code

A state machine usually becomes a switch over a state variable. A generator lets you write the states as sequential code, since the position in the function is the state.

JavaScript
function* trafficLight() {
  while (true) {
    yield "green";
    yield "yellow";
    yield "red";
  }
}

const light = trafficLight();

console.log([1, 2, 3, 4, 5].map(() => light.next().value));
Text
[ 'green', 'yellow', 'red', 'green', 'yellow' ]

That is the trivial case. A more useful one is a protocol where the next expected input depends on the previous one, such as a login handshake.

JavaScript
function* loginFlow() {
  const user = yield "username?";

  if (!user) return "rejected";

  const pass = yield "password?";

  return pass === "secret" ? `welcome ${user}` : "wrong password";
}

const flow = loginFlow();

console.log(flow.next().value);
console.log(flow.next("ada").value);
console.log(flow.next("secret").value);
Text
username?
password?
welcome ada

Each yield is a state, and the if is a transition. Written as a class with a state field and a switch, the same logic spreads across a method and several branches. The generator keeps the order of events visible in the order of the lines, which is what makes it good for wizards, parsers and protocol handlers. The caution is that the state is hidden inside the paused function, so you cannot serialize it or inspect it from outside, which a plain state object allows.

3. Unique id sequences

An id generator is a small private counter that hands out values on demand.

JavaScript
function* ids(prefix) {
  let n = 1;

  while (true) {
    yield `${prefix}-${String(n).padStart(3, "0")}`;
    n += 1;
  }
}

const orderIds = ids("ORD");

console.log(orderIds.next().value, orderIds.next().value, orderIds.next().value);

const invoiceIds = ids("INV");

console.log(invoiceIds.next().value);
Text
ORD-001 ORD-002 ORD-003
INV-001

Each call to ids creates an independent sequence with its own counter. A closure () => n++ does the same job with one line, so use a generator only when the sequence has structure, such as a prefix and a pattern, or when you want take-style helpers to read from it.

4. Chunked work that yields control

A long synchronous task blocks the event loop: no timers, no requests, no input handling until it finishes. A generator can split the task into slices, each yielding after a fixed amount of work, and a driver runs one slice per turn of the loop.

JavaScript
function* sumRange(n, chunk) {
  let total = 0;

  for (let i = 1; i <= n; i += 1) {
    total += i;

    if (i % chunk === 0) yield total;
  }

  return total;
}

function run(generator, onStep) {
  return new Promise((resolve) => {
    const step = () => {
      const { value, done } = generator.next();

      if (done) return resolve(value);

      onStep(value);
      setImmediate(step);
    };

    step();
  });
}

const progress = [];
const result = await run(sumRange(10, 4), (partial) => progress.push(partial));

console.log(progress, result);
Text
[ 10, 36 ] 55

The task reports after each group of four numbers: 1+2+3+4 = 10, then 10 + 5+6+7+8 = 36, and the final total 55 arrives as the return value, which run resolves with. Between slices, setImmediate returns control to the event loop, so other callbacks can run. This is cooperative scheduling, and it is how some libraries keep an interface responsive during heavy work. For real parallelism, a worker thread is the better answer, and the chunked generator is the lightweight option when the work is not heavy enough to justify one.

5. Async flow driven by a runner

Before async and await, libraries used generators to write asynchronous code that read like synchronous code. A runner takes a generator that yields promises, waits for each and sends the result back in.

JavaScript
function runAsync(genFn) {
  const gen = genFn();

  return new Promise((resolve, reject) => {
    function step(method, arg) {
      let result;

      try {
        result = gen[method](arg);
      } catch (error) {
        return reject(error);
      }

      if (result.done) return resolve(result.value);

      Promise.resolve(result.value).then(
        (value) => step("next", value),
        (error) => step("throw", error),
      );
    }

    step("next");
  });
}

const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

const outcome = await runAsync(function* () {
  const a = yield delay(5, 20);
  const b = yield delay(5, 22);

  try {
    yield Promise.reject(new Error("service down"));
  } catch (error) {
    return `${a + b} despite: ${error.message}`;
  }
});

console.log(outcome);
Text
42 despite: service down

The generator yields a promise, the runner waits for it and calls next with the resolved value, or throw with the rejection, which arrives as an exception at the yield and is caught by the ordinary try/catch. That is exactly what await does, and async functions are this mechanism built into the language. You have no reason to write the runner in new code, and understanding it explains why await behaves as it does: each await is a pause that the engine resumes with a value or an exception.

Delegating with yield*

One more feature completes the picture. yield* hands control to another generator and passes its values through, and the value of the yield* expression is the delegate's return value. That lets you build a large flow from small generators, the way a function calls other functions.

JavaScript
function* greet(name) {
  const reply = yield `hello ${name}`;
  return reply.toUpperCase();
}

function* session() {
  const first = yield* greet("ada");
  const second = yield* greet("linus");

  return [first, second];
}

const s = session();

console.log(s.next().value);
console.log(s.next("hi").value);
console.log(s.next("bye"));
Text
hello ada
hello linus
{ value: [ 'HI', 'BYE' ], done: true }

Values sent in with next travel through the delegation to the inner generator, and its return value comes back to the outer one. This composition is what keeps a long state machine or a multi-step protocol readable.

When not to use a generator

Reach for a generator when the logic naturally pauses and resumes. Do not use one for a plain list of values, where an array or map is simpler, nor for state that must be saved, since a suspended generator cannot be serialized. Remember that generators are single-use: after one finishes, it stays finished, and iterating twice yields nothing the second time. Debugging can also be harder, because the interesting state sits inside a suspended call.

JavaScript
const once = [1, 2, 3].values();

console.log([...once].length, [...once].length);
Text
3 0

The second spread found the iterator already exhausted. If you need to iterate repeatedly, keep a function that creates a fresh generator each time.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("values sent in become the result of yield", () => {
  const g = conversation();
  g.next();
  g.next("Linus");
  assert.equal(g.next(54).value, "Linus is 54");
});

test("a running average updates with each value", () => {
  const g = runningAverage();
  g.next();
  assert.equal(g.next(2).value, 2);
  assert.equal(g.next(4).value, 3);
});

test("the runner turns a rejection into a thrown error", async () => {
  const text = await runAsync(function* () {
    try {
      yield Promise.reject(new Error("x"));
    } catch (error) {
      return error.message;
    }
  });

  assert.equal(text, "x");
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.