If I supply a value to the next
method on a generator, in addition to supplying an expression to the right of the yield
keyword, how is the return value of the yield
resolved?
function* go() {
console.log(yield 'a');
console.log(yield 'b');
}
var g = go();
g.next();
g.next('one');
g.next('two');
Output:
one
two
Object {value: undefined, done: true}
In light of the output, it is the value supplied to the next method that is used over the value returned by the expression to the right of yield
.
Edit: code updated to better reflect my question.
In light of the output, it is the value supplied to the next method that is used over the value returned by the expression to the right of yield.
The value supplied to the next
method is not "used over" the value to the right of yield
. The value supplied to next
is what the yield
expression ultimately evaluates to. Always. The value to the right of the yield
is what is supplied to the consumer of the generator.
It is a two-way communication between the generator and the code consuming the generator.
function* go() {
console.log(yield 'a'); // 'one'
console.log(yield 'b'); // 'two'
}
var g = go();
console.log(g.next()); // { value: 'a', done: false }
console.log(g.next('one')); // { value: 'b', done: false }
console.log(g.next('two')); // { value: undefined, done: true }