Consider the following function:
function* gerador() {
let foo = yield "a"
let bar = yield "b"
let baz = yield "c"
return '${foo} ${bar} ${baz}'
}
let gen = gerador();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
The output will be as follows:
{ value: 'a', done: false }
{ value: 'b', done: false }
{ value: 'c', done: false }
{ value: 'undefined undefined undefined', done: true }
Note that the last console.log(gen.next());
returned undefined
for the variables foo
, bar
and baz
.
What I can not understand is that the expression yield "a"
returns the object { value: 'a', done: false }
but the variable foo
remains undefined
and to assign the value, it would have to pass value
to the next method next()
:
let gen = gerador();
let v1 = gen.next().value;
let v2 = gen.next(v1).value;
let v3 = gen.next(v2).value;
console.log(gen.next(v3));
This would have the expected result:
{ value: 'a b c', done: true }