JavaScriptFundamental (ES6), part 1
Generator as a coroutine with yield in JavaScript
149 a generator as a coroutine that listens
hardWrite a generator that keeps a running total, receiving each amount as the value of its yield expression from next(v). Show that the argument to the very first next is discarded, that return() finishes it and runs its finally, and that every call after that is inert. Then throw an error into it at the suspended yield and catch it inside, delegate with yield* and prove next(v) reaches the inner generator, and show what for...of and spread do with the values you would have sent and with the generator return value.
Stuck? Three hints, smallest first
- 1. The first
next()only runs the body up to the firstyield. There is no suspendedyieldexpression for its argument to become. - 2. So the pairing is off by one:
next(v)supplies the value for theyieldthat the PREVIOUSnextstopped at. - 3.
return()andthrow()both resume the generator at that suspended point, which is why afinallyblock inside it runs.
const trace = [];
function* runningTotal() {
let total = 0;
try {
while (true) {
const amount = yield total; // next(v) makes v the value of this expression
trace.push('received ' + amount);
total += amount;
}
} finally {
trace.push('finally ran at ' + total);
}
}
const till = runningTotal();
const started = till.next('IGNORED'); // only starts the body
const afterFirst = till.next(500);
const afterSecond = till.next(250);
const closed = till.return('till shut');
const afterDone = till.next(999);
const tillTrace = [...trace];
const second = runningTotal();
const discarded = [second.next(1000).value, second.next(1).value];
second.return();
const caught = [];
function* resilient() {
let n = 0;
while (n < 4) {
try {
n += yield n;
} catch (e) {
caught.push(e.message);
n += 1;
}
}
return { n, caught: [...caught] };
}
const tough = resilient();
const t1 = tough.next().value;
const t2 = tough.throw(new Error('bad note')).value; // lands at the suspended yield
const t3 = tough.next(2).value;
const t4 = tough.next(1);
function* upTo(limit) {
for (let i = 1; i <= limit; i++) yield i;
return 'RETURNED';
}
const spread = [...upTo(4)];
const looped = [];
for (const value of upTo(3)) looped.push(value);
const byHand = [];
const manual = upTo(2);
byHand.push(manual.next().value, manual.next().value, manual.next().value, manual.next().done);
function* inner() { const a = yield 'i1'; const b = yield 'i2'; return a + b; }
function* outer() { const sum = yield* inner(); yield 'sum ' + sum; }
const delegating = outer();
const delegated = [delegating.next().value, delegating.next(10).value, delegating.next(5).value];
const once = upTo(2);
const drained = [[...once], [...once]];
const selfIterating = [once[Symbol.iterator]() === once, typeof once.next, typeof once.throw];
console.log('till :', [started, afterFirst, afterSecond]);
console.log('closed :', closed, afterDone, '| trace:', trace);
console.log('first arg :', discarded, '| throw in:', [t1, t2, t3, t4]);
console.log('for...of :', spread, looped, byHand);
console.log('yield* :', delegated, '| exhausted:', drained, selfIterating);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first next only starts the body, and its argument is thrown away', [started, discarded], [{ value: 0, done: false }, [0, 1]]);
test('after that next(v) is the value of the suspended yield, so state accumulates', [afterFirst, afterSecond], [{ value: 500, done: false }, { value: 750, done: false }]);
test('return() finishes it, reports the value you passed and runs the finally', [closed, tillTrace], [{ value: 'till shut', done: true }, ['received 500', 'received 250', 'finally ran at 750']]);
test('and every later next is inert: done stays true and no body runs again', [afterDone.done, afterDone.value === undefined, tillTrace.length], [true, true, 3]);
test('throw() lands at the suspended yield, is caught inside, and the generator carries on', [t1, t2, t3, t4.value.caught], [0, 1, 3, ['bad note']]);
test('the return value only ever arrives on the result whose done is true', [t4.done, t4.value.n], [true, 4]);
test('for...of and spread ignore next arguments and DROP the return value', [spread, looped, byHand], [[1, 2, 3, 4], [1, 2, 3], [1, 2, 'RETURNED', true]]);
test('yield* forwards next(v) inward and evaluates to the inner return value', delegated, ['i1', 'i2', 'sum 15']);
test('a generator is its own iterator and is single-use once exhausted', [drained, selfIterating], [[[1, 2], []], [true, 'function', 'function']]);
A generator is not only a lazy sequence. yield is an expression, and its value is whatever the next next(v) hands back, so the channel runs both ways: the generator sends a value out and receives one in, at the same suspension point. That is a coroutine, and it lets you keep evolving state in ordinary local variables rather than in an object with fields, which is why async/await was originally implemented on top of exactly this shape.
The off-by-one is the part everyone gets wrong. The first next() starts the body; there is no suspended yield waiting, so its argument is discarded with no warning at all — the assertion above shows next(1000) vanishing and the next next(1) proving the total was still 0. If a coroutine needs an initial value, take it as a parameter to the generator function, or spend one priming next() before you send anything.
return() and throw() complete the picture: both resume the generator at its suspension point, so finally blocks run and cleanup is honest, and a throw() caught inside lets the generator recover and keep going. Two consequences to remember. The generator return value is real but almost invisible: it arrives only on the result whose done is true, which is precisely the result for...of and spread discard — put data in yield, not in return. And a generator object is its own iterator, so it is single-use: iterate it twice and the second pass sees nothing, and breaking out of a for...of early calls return() for you.