The documentation says that “You can also provide a parameter to the next method to send a value to the generator.” Where does it sends it to?
For example, take these 3 generators:
function* one() { while(true) { var value = yield null; } } var g1 = one(); g1.next(); g1.next(1000); //yields null function* two() { var i = 0; while (true) { i += yield i; } } var g2 = two(); g2.next(); g2.next(1000) // yields 1000 function* three(){ var index = 0; while (true) yield index++; } g3 = three(); g3.next(); g3.next(1000); // yields 1
In generators 3 and 1, the argument passed has no effect on
next
. Why is that? How does generator 2 calculates its return value? Why it is affected by the given argument?
Answer
The key to understanding this is knowing how the next function retrieves the argument passed to next()
, which is as the return value of the yield operator:
[rv] = yield [expression];
Independently of the value of [expression], yield will assign to rv
the value passed to next()
.
But, here comes the tricky part: yield will only assign the value passed to next() when resuming execution from a previous iteration. As a consequence, on the first iteration, yield
does not assign anything to rv.
For example, if I have this generator:
function* gen() {
// On the first iteration, yield does not return anything.
//because it returns something ONLY when execution is resumed
returnedFromYield = yield 'foo';
yield returnedFromYield;
}
returnedFromYield
is undefined on the first iteration. When execution is resumed on the second iteration, yield assigns the passed value to the returnedFromYield
variable, which is then returned:
g.next(1); // 'foo'
g.next(2); // 2
Let’s review another example:
function* gen() {
yield yield yield 5;
}
On the first iteration, (g.next()
), yield will return 5, on the second iteration, (g.next(10)
) yield is going to pass 10 to the second yield. That is, yield yield yield 5;
on the second iteration is equivalent to yield yield 10;
, and, on the third iteration, it’s equivalent to yield valuePassedToNext
.
Attribution
Source : Link , Question Author : Federico , Answer Author : Federico