We can use Promise.all() to wait multiple promises to resolve before going on with our code.
But there is a small problem here... When we use Promise.all(), if ONE of the promises is rejected because of an error, we lose the data from all the other promises that successfully fulfilled and returned data.
PromiseAll.js
const responses = await Promise.all([
getPosts(),
getUsers(),
getShops(),
getPrices()
]).catch(console.error)
for (const response of responses){
// do stuff with your responses array loop
console.log(response.data)
}
console.log(reponses)
//if an Error 404 happens on getPrices(), above code will return the following
---
But what if we want to keep the data from the resolved promises ?
That's where Promise.allSettled() comes into play
let's adapt our code a little bit
PromiseAllSettled.js
const responses = await Promise.allSettled([
getPosts(),
getUsers(),
getShops(),
getPrices()
]).catch(console.error)
// Promise.allSettled() returns information about all the promises in the array
for (const response of responses){
// Check if promise was rejected
if (response.status === 'rejected') continue;
// do stuff with your resolved promise data.
console.log(response.value)
}
console.log(responses)
Promise.allSettled() will fire when all our promises have been fulfilled or rejected.
We then use if (response.status === 'rejected') continue to skip promises that rejected and continue with the rest of them, keeping their results in the process.