ES6 generators mechanism - first value passed to next() goes where?
Also had a hard time wrapping my head around generators, especially when throwing in if-statements depended on yielded values. Nevertheless, the if-statement was actually what helped me getting it at last:
function* foo() {
const firstYield = yield 1
console.log('foo', firstYield)
const secondYield = yield 3
console.log('foo', secondYield)
if (firstYield === 2) {
yield 5
}
}
const generator = foo()
console.log('next', generator.next( /* Input skipped */ ).value)
console.log('next', generator.next(2).value)
console.log('next', generator.next(4).value)
/*
Outputs:
next 1
foo 2
next 3
foo 4
next 5
*/
Everything immediately became clear once I made this realization.
Here's your typical generator:
function* f() {
let a = yield 1;
// a === 200
let b = yield 2;
// b === 300
}
let gen = f();
gen.next(100) // === { value: 1, done: false }
gen.next(200) // === { value: 2, done: false }
gen.next(300) // === { value: undefined, done: true }
But here's what actually happens. The only way to make generator execute anything is to call next()
on it. Therefore there needs to be a way for a generator to execute code that comes before the first yield.
function* f() {
// All generators implicitly start with that line
// v--------<---< 100
= yield
// ^-------- your first next call jumps right here
let a = yield 1;
// a === 200
let b = yield 2;
// b === 300
}
I got this from Axel Rauschmayer's Exploring ES6, especially 22.4.1.1.
On receiving a .next(arg)
, the first action of a generator is to feed arg
to yield
. But on the first call to .next()
, there is no yield
to receive this, since it is only at the end of the execution.
Only on the second invocation x = 1 + 43
is executed and subsequently logged, and the generator ends.
I ended up writing this kind of code to investigate the behavior more thoroughly (after re-re-...-reading the MDN docs on generators):
function* bar() {
pp('in bar');
console.log(`1. ${yield 100}`);
console.log(`after 1`);
console.log(`2. ${yield 200}`);
console.log(`after 2`);
}
let barer = bar();
pp(`1. next:`, barer.next(1));
pp(`--- done with 1 next(1)\n`);
pp(`2. next:`, barer.next(2));
pp(`--- done with 2 next(2)\n`);
pp(`3. next:`, barer.next(3));
pp(`--- done with 3 next(3)\n`);
which outputs this:
in bar
1. next: { value: 100, done: false }
--- done with 1 next(1)
1. 2
after 1
2. next: { value: 200, done: false }
--- done with 2 next(2)
2. 3
after 2
3. next: { value: undefined, done: true }
--- done with 3 next(3)
So apparently the correct mental model would be like this:
on first call to
next
, the generator function body is run up to theyield
expression, the "argument" ofyield
(100
the first time) is returned as the value returned bynext
, and the generator body is paused before evaluating the value of the yield expression -- the "before" part is crucialonly on the second call to
next
is the value of the firstyield
expression computed/replaced with the value of the argument given to next on this call (not with the one given in the previous one as I expected), and execution runs until the secondyield
, andnext
returns the value of the argument of this second yield -- here was my mistake: I assumed the value of the firstyield
expression is the argument of the first call tonext
, but it's actually the argument of the second call tonext
, or, another way to put it, it's the argument of the call tonext
during whose execution the value is actually computed
This probably made more sense to who invented this because the # of calls to next
is one more times the number of yield
statements (there's also the last one returning { value: undefined, done: true }
to signal termination), so if the argument of the first call would not have been ignored, then the one of the last call would have had to be ignored. Also, while evaluating the body of next, the substitution would have started with the argument of its previous invocation. This would have been much more intuitive imho, but I assume it's about following the convention for generators in other languages too and consistency is the best thing in the end...
Off-topic but enlightening: Just tried to do the same exploration in Python, which apparently implements generators similar to Javascript, I immediately got a TypeError: can't send non-None value to a just-started generator
when trying to pass an argument to the first call to next()
(clear signal that my mental model was wrong!), and the iterator API also ends by throwing a StopIteration
exception, so no "extra" next()
needed just to check if the done
is true (I imagine using this extra call for side effects that utilize the last next argument would only result in very hard to understand and debug code...). Much easier to "grok it" than in JS...