yes, it is a good question I will give you an example that will solve your doubt.
Promise.all([
Promise.resolve(20),
Promise.reject("there was an error"),
new Promise((resolve) => setTimeout(() => resolve(30), 300)),
])
.then((values) => console.log(values))
.catch((err) => console.error(err));
Promise.allSettled([
Promise.resolve(20),
Promise.reject("there was an error"),
new Promise((resolve) => setTimeout(() => resolve(30), 300)),
]).then((values) => console.log(values));
In the promise.all if a call fails then it will not enter the then but it will go directly to the catch.
But if you need it to return everything with its states you can use Promise.allSettled which will return an array with the status of each of the promises
script log
❯ node index.js
there was an error
[
{ status: 'fulfilled', value: 20 },
{ status: 'rejected', reason: 'there was an error' },
{ status: 'fulfilled', value: 30 }
]
Agree with you @jordan Jaramillo. Btw, we can also use Promise.all to resolve this problem. Assume that we're fetching many requests. If one of them is successful, we'll return:
yes, it is a good question I will give you an example that will solve your doubt.
In the promise.all if a call fails then it will not enter the then but it will go directly to the catch.
But if you need it to return everything with its states you can use Promise.allSettled which will return an array with the status of each of the promises
script log
Agree with you @jordan Jaramillo. Btw, we can also use Promise.all to resolve this problem. Assume that we're fetching many requests. If one of them is successful, we'll return:
Otherwise
How about your thought?
The problem with promise.all is that you will not be able to access which ones were resolved correctly since it directly passes to the catch.
I mean that if any request is failed, we still use
resolve
instead ofreject
. We only change the returned status.yes, you can do it that way, it's a good idea I hadn't thought about it but if you want to have it automatically you can use allSettled.
Agree !!!