Delegate JavaScript (ES6) generator iteration control

Max Stoiber
InstructorMax Stoiber
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

We can execute generators from generators, and delegate the iteration control with the yield* keyword.

Yo dawg, I heard you like generators, so I put generators inside your generators.

[00:00] Here, we have a very simple generator called createCounter which yields the values 1, 2, and 5. If we iterate over it with a for...of loop, it will log 1, 2, and 5. Yes, everything works as expected.

[00:23] Now, let's say we have a second generator called createThreeToFourCounter, which yields the values 3 and 4. Now, we want to put that in between the yield 2 and the yield 5, but we don't want to manually iterate over it. Thankfully, the yield keyword has something similar to the function keyword.

[00:50] If you type yield* and then a generator, in our case, createThreeToFourCounter, what happens is that this createCounter generator delegates its control to the createThreeToFourCounter. If we execute this code, notice how we didn't change anything about the for...of loop, still the exact same, but if we execute this, it actually logs all the values from 1, 2, 3, 4, to 5.

[01:16] An interesting side effect of this is that we can actually return a value from the delegated generator, and then get that value in our other generator.

[01:26] We can say const four = yield createThreeToFourCounter, and then just console.log four out manually. If we execute this, we get the exact same result as the last time, 1, 2, 3, 4, 5, but this time, we return 4 and then console.log logged it out manually. Communication between two different generators is also possible.

Vamshi
Vamshi
~ 7 years ago

Can you help me understand how 3 was consoled out when we returned only 4?

Anshuman
Anshuman
~ 7 years ago

Because of the

yield 3

line in create3To4Counter()

Dash
Dash
~ 7 years ago

When in the world would we ever use this?

Markdown supported.
Become a member to join the discussionEnroll Today