Asynchronous Iteration using for-await-of

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 2 months ago

The for-await-of syntax is similar to the for-of iteration. The key difference is that it automatically awaits any promises generated by the iterator. This lesson covers how to consume async data sources easily with for-await-of.

for-await-of essentially allows you to use async/await in a generator function.

Instructor: [00:01] Here we have a simple generator function that returns numbers one by one. We increment the number. If it becomes more than 10, we stop.

[00:14] We can use this generator function in a standard synchronous JavaScript with a simple for-of loop. We simply log out the number. If we go ahead and run this example, you can see that it works as expected.

[00:31] Let's imagine that we are going to get the next number from an external source, like a back-end service that will perform its magic to increment the index. We go ahead and import a function that returns the next index from the server. Instead of simply incrementing the index, we will call this function on the previous index to get a new one.

[00:58] Here we have a type mismatch. We have a promise to a number. We would really like to have the result number to make our decision for loop domination. This can be done easily with async/await. We go ahead and make the generator function async and use the await operator on the function return value. Now, the index will result for us and the code compile is fine.

[01:27] Before for-await-of, generator functions could not be async. This new feature requires a run-time polyfill to work correctly, called the async iterator symbol. We can provide it here easily by checking if it already exists or creating it. Ideally, you would use something like GoJS to provide this polyfill for you.

[01:53] This number's function is an async generator and returns an async iterator. Similar to how we use for-of loops with synchronous iterators, we can use for-await-of loops with async iterators. Here you can see that the for-await-of works as expected, getting a number asynchronously, one by one, and logging it out.

[02:21] To summarize, when you want to use async/await in generators, you can use for-await-of to iterate its results.

Basarat Ali Syed
Basarat Ali Syedinstructor
~ 4 years ago

Indeed TypeScript can be used as a very transparent layer on JavaScript. That is one of the strengths of TypeScript 🌹

Basarat Ali Syed
Basarat Ali Syedinstructor
~ 3 years ago

It is all TS files and typescript execution. TypeScript truly is just as simple as JS and shouldn’t need to be anything more if not required : 🌹