Sub topic 9
How Generators Run: Pausing, Resuming, and Finishing
This chapter assumes you know how to write a generator function with function* and yield, and that you can read the { value, done } results returned by next(). Here you will learn when the code inside a generator actually runs, and what happens once it finishes.
The four states of a generator
A generator object is always in one of four states:
- Suspended at start: the generator object exists, but none of its body has run.
- Executing: the body is running, because something called
next(). - Suspended at a yield: the body is paused on a
yieldand waiting for the nextnext()call. - Completed: the body has returned, run off its end, or thrown an error. It will never run again.
Tracing execution step by step
Logging inside the body shows exactly when each piece of it runs:
function* steps() {
console.log('start');
yield 1;
console.log('resumed');
yield 2;
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());Output:
created
start
{ value: 1, done: false }
resumed
{ value: 2, done: false }
end
{ value: undefined, done: true }
{ value: undefined, done: true }Calling steps() prints nothing, so the body starts lazily. Each next() runs the body only up to the next yield and then hands control back to the caller. Local variables and the current position in the code are kept between calls, so resumed continues exactly where the body left off. After the body ends, every later next() returns { value: undefined, done: true }. If the body ends with return x, the caller sees x once, alongside done: true. After that the value is undefined.
Errors end the generator
An uncaught error inside the body passes up through the next() call that resumed it. The generator is then completed:
function* fragile() {
yield 'ok';
throw new Error('boom');
}
const f = fragile();
console.log(f.next()); // { value: 'ok', done: false }
try {
f.next();
} catch (e) {
console.log(e.message); // boom
}
console.log(f.next()); // { value: undefined, done: true }Common errors
| Mistake | What actually happens |
|---|---|
| Expecting side effects when you call the generator function | Nothing runs until the first `next()` |
| Calling `next()` again after an error and expecting a retry | The generator is completed and returns `done: true` |
| Calling `g.next()` from inside `g`'s own body | `TypeError`, because the generator is already running |
Exercise
What does this code print, in order? function* g() { console.log('A'); yield 1; console.log('B'); return 2; } const it = g(); console.log('C'); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value);
Show answer
C, A, 1, B, 2, undefined. Creating the generator runs nothing. The first next() prints A and yields 1. The second next() prints B and returns 2 with done: true. The generator is then completed, so the third next() gives undefined.