Sub topic 12
Sending Values In: next(value), throw(), and return()
This chapter assumes you know how a generator pauses at yield, resumes on next(), and finishes with { done: true }, as covered in the chapter on how generators run. You should also be comfortable with try...catch and with reading { value, done } results by hand.
So far, values have flowed one way: the generator yields and the caller receives. A generator object has three methods that let the caller push something back in:
next(value)resumes the generator, andvaluebecomes the result of the pausedyieldexpression.throw(error)resumes the generator by throwingerrorat the pausedyield.return(value)resumes the generator as if areturn value;statement sat at the pausedyield.
Each method resumes the generator from the same paused point. They differ only in what happens at that point.
next(value): the yield expression has a result
yield is an expression. When the generator pauses at yield x, it hands x out. When it resumes, the whole yield x expression evaluates to whatever the caller passed to the next next() call.
function* runningTotal() {
let total = 0;
while (true) {
const n = yield total;
total += n;
}
}
const acc = runningTotal();
console.log(acc.next()); // { value: 0, done: false } (starts the generator)
console.log(acc.next(5)); // { value: 5, done: false }
console.log(acc.next(10)); // { value: 15, done: false }
console.log(acc.return(99)); // { value: 99, done: true }Walk through it line by line:
acc.next()runs the body from the top until it reachesyield total. It hands out0and pauses before the assignment tonhappens.acc.next(5)resumes. The pausedyield totalevaluates to5, sonis5,totalbecomes5, the loop repeats, andyield totalhands out5.acc.next(10)makesnequal10andtotalequal15.acc.return(99)finishes the generator. The next section of this chapter covers it.
The first next() argument is discarded
The first next() call has no paused yield to deliver a value to, because the body hasn't started yet. Any argument you pass is silently dropped.
function* echo() {
const first = yield 'started';
console.log('received', first);
}
const e = echo();
console.log(e.next('lost')); // { value: 'started', done: false }
console.log(e.next('kept')); // logs: received kept
// { value: undefined, done: true }This is why code that feeds a generator usually "primes" it with an empty next() first. If you do this often, a small wrapper helps:
function primed(genFn) {
return (...args) => {
const gen = genFn(...args);
gen.next(); // run to the first yield
return gen;
};
}
const logger = primed(function* () {
while (true) {
const msg = yield;
console.log('log:', msg);
}
});
const log = logger();
log.next('hello'); // log: hello
log.next('world'); // log: worldParenthesize yield inside larger expressions
yield has very low precedence, about as low as assignment. const n = yield total; is fine, but in a larger expression you need parentheses:
function* greet() {
const line = 'Hello, ' + (yield 'name?');
yield line;
}
const g = greet();
console.log(g.next().value); // name?
console.log(g.next('Ada').value); // Hello, AdaWithout the parentheses, 'Hello, ' + yield 'name?' is a syntax error.
throw(error): raising an error at the pause point
gen.throw(err) resumes the generator and throws err from the paused yield, exactly as if that line contained throw err. If the generator catches it, it can keep going. Whatever the generator yields next becomes the result of the throw() call.
function* resilient() {
while (true) {
try {
const value = yield 'ready';
console.log('got', value);
} catch (err) {
console.log('caught', err.message);
}
}
}
const r = resilient();
console.log(r.next()); // { value: 'ready', done: false }
console.log(r.next('a')); // got a, then { value: 'ready', done: false }
console.log(r.throw(new Error('bad'))); // caught bad, then { value: 'ready', done: false }If the generator doesn't catch the error, the error propagates out of the throw() call to the caller, and the generator is finished for good:
function* fragile() {
yield 1;
yield 2;
}
const f = fragile();
f.next();
try {
f.throw(new Error('boom'));
} catch (e) {
console.log('caller caught', e.message); // caller caught boom
}
console.log(f.next()); // { value: undefined, done: true }Edge case: throw() before the first next()
A generator that hasn't started has no yield to throw at, and its try blocks haven't been entered. Calling throw() on it finishes the generator immediately and rethrows the error to the caller. No catch block inside the body runs.
function* guarded() {
try {
yield 1;
} catch {
console.log('never printed');
}
}
const it = guarded();
try {
it.throw(new Error('early'));
} catch (e) {
console.log(e.message); // early
}
console.log(it.next()); // { value: undefined, done: true }return(value): finishing from outside
gen.return(value) acts like a return value; statement at the paused yield. The generator completes, and the call returns { value, done: true }. Calling it on a generator that hasn't started completes it without running any of the body:
function* never() {
console.log('body ran');
yield 1;
}
const n = never();
console.log(n.return(5)); // { value: 5, done: true } (nothing logged)
console.log(n.next()); // { value: undefined, done: true }for...of calls this method for you when you break, return, or throw out of a loop. That is how the iterator return() method from the early-exit chapter applies to generators.
The three methods across generator states
| Method | Not started yet | Paused at `yield` | Already finished |
|---|---|---|---|
| `next(v)` | Runs body to first `yield`; `v` ignored | `yield` evaluates to `v` | `{ value: undefined, done: true }` |
| `throw(e)` | Finishes; `e` thrown to caller | `e` thrown at the `yield` | `e` thrown to caller |
| `return(v)` | Finishes; `{ value: v, done: true }` | Acts as `return v` (finally blocks run) | `{ value: v, done: true }` |
yield* forwards all three methods
When a generator delegates with yield*, calls to next(v), throw(e), and return(v) on the outer generator pass through to the inner one while delegation is active:
function* inner() {
try {
yield 'inner';
} catch (e) {
console.log('inner caught', e.message);
yield 'recovered';
}
}
function* outer() {
yield* inner();
yield 'outer';
}
const o = outer();
console.log(o.next()); // { value: 'inner', done: false }
console.log(o.throw(new Error('x'))); // inner caught x, then { value: 'recovered', done: false }
console.log(o.next()); // { value: 'outer', done: false }This means you can split a value-receiving generator into smaller generators, and callers can still talk to whichever one is running.
When to use this
Use two-way generators for coroutine-style code: accumulators, parsers that receive input one chunk at a time, and small state machines whose state is the current position in the code. Before async/await existed, libraries such as co ran generators that yielded promises and passed the resolved values back in with next(value). Today async functions do that job, and for most data-producing code you will only call next() with no argument. A generator that receives values with next(value) is harder to read than a class with named methods, so choose it when it actually simplifies control flow.
Exercise
Given function* g() { const a = yield 1; const b = yield a * 2; return a + b; } and const it = g();, what do it.next(10), it.next(3), and it.next(4) return, in order?
Show answer
{ value: 1, done: false }, because the first argument (10) is discarded. Next comes { value: 6, done: false }: a is 3, so it yields 3 * 2. Last is { value: 7, done: true }: b is 4, and the generator returns 3 + 4.
Exercise
A generator wraps its only yield in try { ... } catch { ... }. You call gen.throw(new Error('x')) right after creating it. Does the catch block run? What does a later gen.next() return?
Show answer
No. The generator never started, so it never entered the try block. throw() finishes the generator and rethrows the error to the caller. A later gen.next() returns { value: undefined, done: true }.
Exercise
You drive runningTotal (from this chapter) with for (const t of runningTotal()) { console.log(t); if (t > 100) break; }. What does it print, and why?
Show answer
It prints 0, then NaN repeatedly. The loop never ends, because NaN > 100 is false. for...of calls next() with no argument, so n is undefined and total += undefined makes total NaN.