Reputation: 27
I try to understand Generators, but I found an example which I can not follow.
// First Generator
function* Colors ()
{
yield "blue";
yield* MoreColors ();
yield "green";
}
// Generator refered by the first Generator
function* MoreColors ()
{
yield "yellow";
yield "orange";
}
// Let us iterate over the first Generator
const colorIterator = Colors();
let color;
while (!(color = colorIterator.next()).done)
{
console.log(color.value);
}
The output is: "blue" "yellow" "orange" "green"
I expected: "blue" "yellow" "orange"
Why I expected this: I think that after orange has been returned, the method .next() is called on the Iterator from MoreColors (). This should return an object with the propery value true for the property .done. By this, item is equals true and the while-loop should stop.
Obviously, my expectations are wrong.
I would be glad, if someone could point out what I get wrong.
Upvotes: 1
Views: 104
Reputation: 1292
The problem is that the generator Colors does not stop once MoreColors stops. After MoreColors is done, the execution of Colors continues from where it stopped, and so it would return "green" before being done. That's because the generator does not "become" MoreColors, but rather returns its answers, and the .next() method is still called on Colors.
Upvotes: 1