Use JavaScript (ES6) generators to pause function execution

Max Stoiber
InstructorMax Stoiber
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

ES6 generators make it possible to pause and resume function execution at arbitrary points. This video will introduce you to the basics of generators with the yield keyword.

[00:00] In JavaScript, functions execute until they've reached a return keyword or the end of the function. If we execute our logger here and run it with Node, you will see that it first logs start, and it then logs end. EA6 generators are different. They can be paused and resumed at arbitrary points within the function.

[00:21] To create a generator, we put an asterisk after the function keyword. If we execute this file again, you will see that nothing happens. Nothing is console.logged out. That is because when we call a generator, it returns an instance of itself but doesn't execute it.

[00:40] To be more exact, we should call our generator create logger, and assign it to a variable called logger. To execute our generator, we call logger.next, which executes until the next block is over. If we run this, you'll see again that we logged start and we logged end.

[00:59] To pause a generator, we use the yield keyword. The yield keyword tells the generator to stop executing at this point. If we run our file again, you will see this logs out start. The generator never reaches the console.log end. To execute the next block as well, we call logger.next again. As you can see, both start and end were logged out.

[01:26] We can have as many of these yield keywords in our generator as we want. If we say console.log second block and third block here, and then call logger.next a bunch of times, if we execute this, you will see that everything executes as you expect.

egghead
egghead
~ 13 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today