Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Send messages to and from JavaScript (ES6) generators

    Max StoiberMax Stoiber

    We can communicate between generators and their instances with strategically placed yield keywords. This video will show you how to make it happen based on a simple example.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 We have a generator here and an instance of a generator. These two can communicate. You can send messages from the instance of the generator back to the generator function, and you can send messages from the generator itself to the instance of the generator.

    00:15 Let's say we want to send a message from the generator to our instance of the generator. We can do so with a yield keyword, putting any value that we want to the right of it. This value will now be returned from the hello.next call that we do, which pauses the generator, this yield keyboard, and returns this value.

    00:33 If we run our function, we will see that it doesn't only return the value, but it actually returns an object which has a value property of first, which is the value we pass through, and another property called done, which is currently set to false.

    00:50 Done is set to false because we haven't yet finished executing our generator. It is still paused at this yield keyword. To finish executing the generator, we simply call hello.next again. The second log that I've put out, now has a value of undefined, but done is true now because our generator is now at the end of the function and has finished executing.

    01:13 If we want to pass a value from our instance of the generator back to the generator function, we can pass a value when we resume the generator with hello.next and assign it to any variable. In our case, I'll call it word, and then console.logout whatever we pass in.

    01:30 I'm going to pass in a string that says max and start our function again to see what happens. This time, both of our hello.next calls return the value of undefined. We also got max logged out because we logged out the word which we passed in when we resumed the generator.

    Discuss

    Discuss