Resolving Multiple Promises

Thursday, March 16th 2023

Q: How do I resolve multiple Promises in ES6?

In ES6, you can use the Promise.all() method to execute multiple promises concurrently and wait for all of them to complete before moving on to the next step in your code. The method takes an array of promises as input and returns a new promise that resolves with an array of results in the order that the promises were passed in.

Here's an example of how to use Promise.all():

const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('Promise 1 resolved'); }, 1000); }); const promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('Promise 2 resolved'); }, 500); }); const promise3 = new Promise((resolve, reject) => { setTimeout(() => { resolve('Promise 3 resolved'); }, 2000); }); Promise.all([promise1, promise2, promise3]) .then(results => { console.log(results); }) .catch(error => { console.error(error); });

In this example, we create three promises that resolve after different amounts of time. We then pass an array containing these promises to Promise.all(). When all three promises have resolved, Promise.all() resolves with an array of the results in the order that the promises were passed in.

The output of this code would be:

[ 'Promise 1 resolved', 'Promise 2 resolved', 'Promise 3 resolved' ]

Note that if any of the promises in the array reject instead of resolving, the Promise.all() call will immediately reject with the error from the first rejected promise. To handle this case, you can use a .catch() block to handle any errors that occur during the execution of the promises.