Generator Functions


Uncategorized

Updated Jul 14th, 2022

function* simpleGenerator() {
	yield 1
	yield 2
	yield 2
}

const generatorObject = simpleGenerator()
//console.log(generatorObject)
const obj = generatorObject.next()
console.log(obj)

When you call the generator function, the very first time it doesn’t do anything but create an object.

Note: you can have multiple generators happening at once.

Use cases: When you want to run an infinite loop. Won;t freesze your computer because you are only runnign it one step at a time. Let’s say you want it to generated ids you could have:

function* generateId() {
let id = 1
while (true) {
  yield id
  id++
}
}

You can pass a a value to next() can get returned from yield to be used in the next iteration. passing a value to yield does nothing on the first iteration.

Note: Can also use a generator as an iterator. Do something like, while not done, then do something. This is common in certain libraries.

Exit out of a generator by using .return() and can throw an error using .throw()

Sources

Here