July 15, 2021
How does this work? Generators! Also known as Generator Functions.
A generator function can be paused at any given point and continue where it left off when told to do so. Pretty crazy, right?
Let's take a look at a basic example.
The difference is in the function definition itself - generator functions are written using the
You probably noticed the
yield keyword in the example above. When a generator function is called, it executes until it encounters a
yield expression. At this point, the generator function pauses, returns the value defined after the
yield keyword, and waits to continue execution until the function is called again.
If we wanted to get the data in the
tacoIngredients function defined in the example above, it would look something like this:
Each time we call the
next() method, an object is returned in the shape mentioned prior. To get the data, simply access the
value property. Because the
done property has a value of false, we know there is more data to be retrieved and we can call the generator again.
If we call
next() after the generator has encountered its last
yield keyword, it returns an object with a single property - and it's probably what you're expecting -
done is set to true!