Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Asynchronous Iteration using for-await-of

    Basarat Ali SyedBasarat Ali Syed

    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.

    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss