Jim Jim - 1 year ago 90
Javascript Question

Iterate over Generator which returns a Generator

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)

The output is:

I expected:

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download