Another way to take advantage of concurrency when we have multiple promises which can be executed simultaneously is to await a Promise.all().
We can pass an array of promises as the argument to Promise.all(), and it will return a single promise. This promise will resolve when all of the promises in the argument array have resolved. This promise’s resolve value will be an array containing the resolved values of each promise from the argument array.
async function asyncPromAll() {
const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
for (let i = 0; i<resultArray.length; i++){
console.log(resultArray[i]);
}
}
Promise.all() allows us to take advantage of asynchronicity— each of the four asynchronous tasks can process concurrently. Promise.all() also has the benefit of failing fast, meaning it won’t wait for the rest of the asynchronous actions to complete once any one has rejected. As soon as the first promise in the array rejects, the promise returned from Promise.all() will reject with that reason. As it was when working with native promises, Promise.all() is a good choice if multiple asynchronous tasks are all required, but none must wait for any other before executing.
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('one'), 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 2000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('three'), 3000);
});
const p4 = new Promise((resolve, reject) => {
setTimeout(() => resolve('four'), 4000);
});
const p5 = new Promise((resolve, reject) => {
reject(new Error('reject'));
});
// Using .catch:
Promise.all([p1, p2, p3, p4, p5])
.then(values => {
console.log(values);
})
.catch(error => {
console.error(error.message)
});
//From console:
//"reject"