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:

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.

Elsewhere , ,

Leave a Reply

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.