I tried small piece of code for generators
function* listener() {
console.log('listening');
while (true) {
console.log('before yield'); /** Why this is getting print in end again**/
let msg = yield;
console.log('after yield', msg);
}
}
let l = listener();
l.next('are you there?');
console.log('-----');
l.next('how are you?');
Output:
listening
before yield
-----
after yield how are you?
before yield
Everything looks ok but the only thing which I am not sure about how come control going back to print 'before yield' in the end again.
Could someone help me out here to understand the concept.
Thanks
First note that passing an argument to the first call of next
has no use: this value is only relevant when the generator function has encountered a yield
expression. Be aware that the generator function executes nothing until the first next
call is made.
When you call next
the first time, the generator function starts executing from the top until it encounters yield
. There its execution is suspended.
When you make the second next
call, the argument you passed determines the value of the yield expression. The generator function resumes execution and assigns that value to msg
and then continues up until the next yield
. This is where the output is made where you wonder about.
Here's a visualisation:
main | listener |
---|---|
let l = listener(); |
|
l.next('are you there?'); |
|
console.log('listening'); |
|
while (true) { |
|
console.log('before yield'); |
|
yield |
|
(suspend) | |
console.log('-----'); |
|
l.next('how are you?'); |
|
(resume) | |
msg = 'how are you?'; |
|
console.log('after yield', msg); |
|
while (true) { |
|
console.log('before yield'); |
|
yield |
|
(suspend) |