Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Created June 21, 2018 18:36
Show Gist options
  • Select an option

  • Save beardedtim/f151c4c7d2b1db8e097aed733d1a033a to your computer and use it in GitHub Desktop.

Select an option

Save beardedtim/f151c4c7d2b1db8e097aed733d1a033a to your computer and use it in GitHub Desktop.

Generator Functions

What are they?

generator functions are a special type of functions in JavaScript that allows for exiting and re-entering of functions. Instead of a functions always running to completion, a generator function can be exited and re-entered many times via the yield keyword. Example:

const fn = () => {
  doSomething()
  doSomethingElse()
  doAnotherThing()
}

fn()

In the code above, you can know without a shadow of a doubt that, when you call fn(), the function doSomething() will be called and immediately after that, doSomethingElse, and then doAnotherThing without ever leaving the function. At no point inside of fn can we say "Hey, stop what you're doing and let me take control of the thread over here and I'll come back to you". To do that, we need generator functions:

function* fn() {
  yield doSomething()
  yield doSomethingElse()
  yield doAnotherThing()
}

const gen = fn()

const didSomething = gen.next().value
const didSomethingElse = gen.next().value
cosnt didAnotherThing = gen.next().value

Here, we define fn as a generator function. Which means, we can exit the function before it finishes and at some point in the future, revisit the function.

Okay....but what are they?

This video ( and funfunfunctions in general ) is an amazing resource for this. If videos aren't your thing, these blogs/tuts are what I lean on, besides MDN:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment