Recently I saw a colleague implement some functionality in which he required two results from an API using async
–await
. 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 singlePromise
that resolves when all of the promises in theiterable
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.
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!