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

Autoplay

    Await Multiple Promises Sequentially or Concurrently

    Marius SchulzMarius Schulz

    You can await multiple promises either sequentially or concurrently, depending on where you put the await operators. This lesson shows both approaches and compares the performance characteristics.

    javascriptJavaScript
    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

    00:00 In this lesson I want to make two calls to the GitHub API. I want to load a user's profile and then also a list of their repositories. The straightforward way to do this would be to make two sequential HTTP requests. We could first load the user and then await the response and then do the same for the repositories.

    00:22 Once we have both responses, we want to log the user's name to the console and then also the number of their repositories. This should be enough to run our program and see some output, so let's head over to the terminal and say node async.js.

    00:41 Yep, there we go -- we have a name and a repository count. Now, the problem with this program is that the HTTP requests are made sequentially and not in parallel. This is because we're only making the second HTTP request after the first one has already completed. This can cause performance problems in our applications.

    01:04 If every request takes about half a second to complete, making two requests already costs us one second. You can compare this to boiling eggs for breakfast. Instead of cooking one after the other, you would boil them all at the same time, right?

    01:19 All right, let's fix our code. Let's first get rid of the await operator here and then rename the variables to include the promise suffix, because now we're storing the promises in the variables, and not the results.

    01:34 We now have two concurrently running HTTP requests. We are not waiting for the first one to finish before we make the second one. Down below, we can now say const user=await user promise and do the same for the repositories.

    01:54 Notice that this approach is different from the one we used before. We are now kicking off both requests at the same time and then we are waiting for both to come back. The slower of the two promises determines how long this entire operation takes, and we are no longer incurring the performance hit of awaiting two HTTP requests sequentially.

    Discuss

    Discuss