Sub topic 9
How Generators Run: Pausing, Resuming, and Finishing
This chapter assumes you can write a basic generator with function* and yield, and that you know the iterator protocol: next() returns { value, done }. You should also be comfortable with closures and try...catch. Here we look at what happens at runtime, step by step. You will learn when the body starts, where it stops, what it keeps between calls, and how it ends.
The generator object is a paused function call
Calling a normal function runs its body right away. Calling a generator function does not run any of the body. It creates a generator object, which is a function call that has been set up and then paused before its first line. The arguments are bound and the local scope exists, but no statement has executed yet.
Each call to next() resumes the body. The body runs until one of three things happens:
- It reaches a
yield. The generator pauses, andnext()returns{ value: <yielded value>, done: false }. - It reaches a
returnor the end of the body. The generator finishes, andnext()returns{ value: <return value>, done: true }. If the body just runs off the end, the value isundefined. - It throws an exception that nothing inside the body catches. The generator finishes, and the exception comes out of the
next()call.
Logging at each step shows this order:
function* steps() {
console.log('start');
yield 'A';
console.log('between');
yield 'B';
console.log('end');
}
const g = steps();
console.log('created');
console.log(g.next());
console.log(g.next());
console.log(g.next());
console.log(g.next());
// created
// start
// { value: 'A', done: false }
// between
// { value: 'B', done: false }
// end
// { value: undefined, done: true }
// { value: undefined, done: true }'created' prints before 'start' because steps() ran nothing. Each next() runs only the code between one pause point and the next. The last call shows that a finished generator stays finished. Every later next() returns { value: undefined, done: true } without running anything.
The four states
The specification tracks a generator's state internally. You cannot read the state directly, but knowing the four states makes the behavior easy to predict.
| State | Meaning | What `next()` does |
|---|---|---|
| suspended-start | Created, body not started | Starts the body from the first line |
| suspended-yield | Paused at a `yield` | Resumes right after that `yield` |
| executing | Body is running right now | Throws `TypeError` (re-entry is not allowed) |
| completed | Returned, ran off the end, or threw | Returns `{ value: undefined, done: true }` |
The diagram leaves out the shortcuts that return() and throw() provide. Those methods are covered in the chapter on sending values into a generator.
State survives between pauses
When a generator pauses, its whole execution context is saved: local variables, the current loop position, and any enclosing try blocks. Each generator object has its own saved context, so two objects made from the same function never share local state.
function* counter() {
let n = 0;
while (true) {
yield ++n;
}
}
const a = counter();
const b = counter();
a.next();
a.next();
console.log(a.next().value); // 3
console.log(b.next().value); // 1The while (true) loop is safe here. It does not freeze the program, because each pass stops at yield and waits for the caller. The generator does only as much work as the caller asks for. Later chapters on lazy and infinite sequences build on this.
Finishing: return values and errors
A return statement inside a generator sets the value of the final result, and that result always has done: true. It is the only result that carries both a value and done: true. Consumers such as for...of and spread stop when they see done: true and ignore its value, so a return value is seen only by code that calls next() directly or uses yield*.
An uncaught exception also finishes the generator. The error comes out of the next() call that resumed the body, and the generator is then completed:
function* risky() {
yield 1;
throw new Error('boom');
}
const r = risky();
console.log(r.next()); // { value: 1, done: false }
try {
r.next();
} catch (e) {
console.log(e.message); // boom
}
console.log(r.next()); // { value: undefined, done: true }After an error the generator cannot be resumed or restarted. To start over, call the generator function again to get a new object.
Gotcha: argument checks run late
Lazy start has a side effect people often miss. Validation at the top of a generator body does not run when the generator is created. It runs on the first next(), which may be much later and in a different part of the program.
function* repeat(value, times) {
if (times < 0) throw new RangeError('times must be >= 0');
for (let i = 0; i < times; i++) yield value;
}
const it = repeat('x', -1); // no error here
try {
it.next(); // the error appears only now
} catch (e) {
console.log(e.name); // RangeError
}If you want errors to appear at the call site, validate in a normal function and have it return the generator:
function repeat(value, times) {
if (times < 0) throw new RangeError('times must be >= 0');
return repeatGen(value, times);
}
function* repeatGen(value, times) {
for (let i = 0; i < times; i++) yield value;
}
try {
repeat('x', -1); // throws immediately
} catch (e) {
console.log(e.name); // RangeError
}
console.log([...repeat('x', 2)]); // [ 'x', 'x' ]Gotcha: no re-entry
A generator cannot resume itself while it is running. If code in the body calls next() on the same generator, that call throws a TypeError because the generator is already executing.
let gen;
function* selfCall() {
gen.next(); // the generator is executing, so this throws
}
gen = selfCall();
try {
gen.next();
} catch (e) {
console.log(e instanceof TypeError); // true
}The TypeError is thrown inside the body. Nothing in the body catches it, so it escapes through the outer next() and the generator ends up completed. In real code this usually happens by accident, through a callback or event handler that calls back into the generator that triggered it.
Gotcha: yield only works in the generator's own body
yield belongs to the nearest enclosing function, and it is valid only when that function is a generator. You cannot yield from inside a callback such as the one passed to forEach. Inside an ordinary nested function this is a SyntaxError, and an arrow function cannot be a generator at all. Use a plain loop so the yield stays in the generator's own body:
function* doubled(items) {
// items.forEach(x => { yield x * 2; }); would be a SyntaxError
for (const x of items) {
yield x * 2;
}
}
console.log([...doubled([1, 2, 3])]); // [ 2, 4, 6 ]Summary
- Calling a generator function creates a paused call. The body runs only when
next()is called. - Each
next()runs the body up to the nextyield,return, or uncaught throw. - Local variables and loop position survive pauses, and each generator object keeps its own copy.
- After the body returns or throws, the generator is completed, and every later
next()returns{ value: undefined, done: true }. - Lazy start also delays argument checks, re-entering a running generator throws
TypeError, andyieldcannot be used inside nested callbacks.
Exercise
What does this program print, in order? function* g() { console.log('one'); yield 1; console.log('two'); return 2; } const it = g(); console.log('ready'); console.log(it.next().value); console.log(it.next()); console.log(it.next());
Show answer
It prints "ready", then "one", then 1, then "two", then { value: 2, done: true }, then { value: undefined, done: true }. The body does not start until the first next(). The return value appears once, with done: true, and after that the completed generator returns value undefined.
Exercise
A function* parseConfig(text) begins with if (typeof text !== 'string') throw new TypeError('text required'). A teammate writes const p = parseConfig(null); and gets no error. Why, and how would you make the error appear at that line?
Show answer
Calling a generator function runs none of its body, so the check runs only on the first p.next(). To fail at the call site, move the check into a normal function that validates the argument and then returns a call to an inner generator function that does the yielding.
Exercise
After a generator's body throws an uncaught error, a caller catches the error and calls next() again. What happens, and how can the caller start the sequence over?
Show answer
next() returns { value: undefined, done: true } because the generator is completed. It cannot be resumed or reset. To start over, call the generator function again to get a new generator object.