For more tips like this, sign up to the weekly newsletter!

How to await for multiple results in parallel

When using async/await, the usual way of waiting for multiple functions is to either await one after the other, or use a for..of loop:

const result1 = await asyncFunc1();
const result2 = await asyncFunc2();
for(f of [asyncFunc1, asyncFunc2]) {
  console.log(await f());
}

But both of the above approaches process the functions sequentially, i.e. the second one is only started when the first one is finished.

How to process them in parallel?

Let's recall how it's done without async/await, using good old Promises:

Promise.all([asyncFunc1(), asyncFunc2()]).then((results) => {
  console.log(results);
});

Promise.all waits for all the parameter Promises to finish, and the results contains all their results, in order.

To use async/await, the same structure, with some array destructuring sugar achieves a nicer syntax:

const [result1, result2] = await Promise.all([asyncFunc1(), asyncFunc2()]);

This works the same as the first example, but runs the functions in parallel.

Try it
Learn more: