JavaScript asyncawait: Resolving Promises in parallel

Recently I saw a colleague implement some functionality in which he required two results from an API using asyncawait. The piece of code looked something like this:

The code looks fine, is syntactically correct, and works … but there’s one big problem with it: the calls are made sequentially.

To run these calls – which are promises – in parallel, one can reside to using Promise.all.

As per MDN Docs:

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Combine that with destructuring and the code becomes this:

async function fetchData() {
    const [result1, result2] = await Promise.all([
        callApi('https://example.com/endpoint1'),
        callApi('https://example.com/endpoint2'),
    ]);

    // ...
}

Easy, right?

💻 The example embedded in this post is part of a talk on ESNext named “What’s next
 for JavaScript?”, which I recently gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check out the slides / a recording of that talk right here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.