Into Promises: handling multiple

Gaetano Violante

Hopefully you enjoyed my introduction article on ES6 promises and you can click here in case you have miss it.

Here I’m going to show you how to handle multiple promises.
For sake of simplicity suppose you have two promises, the first being faster than the second:

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Promise 1'), 1000);

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Promise 2'), 5000);

We might be interested in the outcome coming from each of them, and the method we are going to use is all(). The final result will be printed out when the slower promise returns, and we’ll see an array ['Promise 1', 'Promise 2'] printed out in the browser console.

The code we need is:

Promise.all([p1, p2]).then((values) => console.log(values));

Other than that, we might be interested in the outcome from the fastest promise, without waiting for all the promises to return.

In this case we can use the race() method, as shown here:

Promise.race([p1, p2]).then((value) => console.log(value));

Here is quite immediate to see that the first promise is the faster than the second, but this might not be if you imagine to an asynchronous calls to an external web service, for instance. This method can result useful in that case.

Hope you enjoy the reading!


you might also like