Here, I have a simple generator, which yields the values 1, 2, and 3. Within the main function, I can use the for...of loop to iterate over every value produced by the generator. I'll add a log statement here, just to make sure everything is working.
Let's run the program, and yes, we see 1, 2, and 3 printed to the console. Let's now see how we can make this generator function asynchronous.
First, I'm going to add the async keyword. Within the generator, I'll add some artificial delays to simulate long-running operations. The delay function doesn't exist yet. I'll add it above the generator function. It simply returns a new promise, which is resolved after a given number of milliseconds.
I will also make the main function asynchronous, and I'll add the await keyword right before the opening parenthesis of the loop. This is a for...await...of loop, a new variation of the for...of loop. It's used for asynchronous iteration.
There are two more things I need to do before I can run this program. First, I will polyfill the async iterator symbol. Here, I'm just monkey-patching it, but in a real application, you would want to use a proper polyfill.
You want to pay close attention to the timing. All right, here we go.
One more time for the dramatic effect.
Notice how the values are printed one after the other, with a delay of one second in between each of them. This is because our asynchronous generator yields three promises, instead of three plain objects.
Our for...await...of loop down here gets back the first promise, and then waits until that promise is resolved. It only then resumes the generator. The generator then returns a second promise, and so on.
I want to close off this lesson by showing roughly what happens in our main function. First, the for...await...of loop instantiates the generator. We then enter a while loop. Within that loop, we await the promise returned by generator.next, and then we deconstruct the result into its value and done properties.
If we are done, we break out of the loop and stop the iteration. After this, if statement comes the loop body. In our case, we log the value property to the console. If I have done everything correctly, we should still see the numbers 1, 2, and 3 printed to the console, and we do.