Generators

We'll cover the following...

ES6 brings us a new type of function, the generator function. Generators are a function that allows us to pause and resume execution. Generators exist in many other languages and are used mostly for control flow.

The syntax to create a generator is the same as a regular function, however we use the * at the end of the function keyword to indicate we are creating a generator.

Press + to interact
function* functionName() {
}

Generators return an Iterator Object, similar to Map, Set, and Array. An Iterator Object is an object that implements a .next() method. This means that our generator function can provide multiple results. There is also a new keyword introduced called yield, the yield keyword is used to actually pause the execution of the function and return the value provided.

Our First Generator

Let’s look at a simple example of a generator.

Press + to interact
function* myGenerator() {
yield "Isn't";
yield "this";
yield "cool!";
}

Inside of the generator we are able to yield as many values as you want. Here we are yielding three times, in order to get at those values we need to call our generator.

Press + to interact
const generatorValues = myGenerator();
console.log(generatorValues.next());
/*
{
value: "Isn't", done: false
}
*/

The next method returns an object that has the two keys on it, value and done. ...