Reputation: 2277
This is from MDN:
gen.next(value)
The value will be assigned as a result of ayield
expression. For example, invariable = yield expression
, the value passed to the.next()
function will be assigned tovariable
.
Also, this is from Medium article:
The second
next(10)
call, replaces the entire firstyield
expression with10
So my question is, how is the next(value)
replacing the "previous" yield expression? how is it working behind the scenes. I have read about iterators but i can't understand how is next()
working in this case.
Upvotes: 1
Views: 363
Reputation: 781058
When a generator executes a yield
statement
variable = yield value;
it sends value
to the most recent caller of next()
. Then it waits for another call to next()
. The value passed as an argument to that call is used as the value of this yield
expression, which is assigned to variable
.
Then it continues with the rest of the code in the generator. The next use of yield
repeats the above process.
It's this way because JavaScript combines sending output and receiving input into a single operation. The first input to the generator comes through the parameter list, all the future inputs come from yield
, which gets the values from the corresponding next()
calls. It has to send to the last yield
because of this order of operations.
Upvotes: 3