This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In


    Execute Promises in Parallel and Serial using async / await

    Basarat Ali SyedBasarat Ali Syed

    The great thing about asynchronous programming is that you can do multiple things in parallel. E.g. you can make multiple network requests, or read multiple files from the file system.

    This lesson covers how to write parallel as well as serial async 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


    Instructor: 00:00 We start off by bringing in a function, get user details. The implementation of this function is not important beyond the fact that it takes a Github user handle, and returns a promise to the details which are resolved asynchronously.

    00:20 In our main application, we have an async main function and that we'll execute upfront. We have a few Github user handles that we want to get the details for. Getting the details for each of these handles one by one is a very easy task with async await.

    00:44 We simply loop through the handles one-by-one with the for-of loop, await the details for a particular user and log them out to the console. Doing such a serial sequence of async events is something that is way too easy, thanks to async await. We can see that we get the details one by one.

    01:10 Sometimes, you might want to run a bunch of operations in parallel and wait for all of them to resolve. This can be done with promise.all. We start off by running all the calls to get user details in parallel. At this point, we have an array of promises that will resolve independently.

    01:33 Promise.all is a native function that takes an array of promises and returns a new promise that resolves with an array of resolved values for each of the promise. Now that we have a single promise, we can await it easily, giving a single array of resolved values. Now, we simply loop over the elements of the array and log it out.

    02:05 If we go ahead and run this demo, you can see that we get all the three results at the same time and that the overall process is much faster as we get the details in parallel. One final native control flow worth mentioning is promise.race.

    02:28 This function takes an array of promises just like promise.all and returns a new promise. The fate of this new promise is equal to the fate of the first promise that resolves or rejects. Here, we simply log out the result of the first promise sequence. In our case, the first promise resolves the fastest. Hence, the result is result of the first go.