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().valueHere, 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.
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: