ES6

Promise.all() VS Promise.allSettled()

promise.all

promise.all

A javascript promise can be compared to a real-life promise like if your dad promises you that he will get you a motorbike when you reach 18 years of age.
Now he might get you a bike which if promise fulfilled or he might not which is like the promise failed.

  • Until you reach age 18, the promise is pending
  • he might get you a bike which if promise fulfilled
  • he might not which is like the promise failed.

Similar to that are JS promises where are 4 states:

  1. fulfilled: Action related to the promise succeeded
  2. rejected: Action related to the promise failed
  3. pending: Promise is still pending i.e not fulfilled or rejected yet
  4. settled: Promise has fulfilled or rejected

Now that’s enough of promises, here in this article we will be not going deep into the promises but we will discuss 2 most important promise methods which are: –

  1. Promise.all()
  2. Promise.allSettled()
Short Circuit whenFulfilled whenRejected When
Promise.all1st promise rejectedAll fulfilled promises1st promise rejected
Promise.allSettled()Not allowedAlwaysNever rejected

Promise.all()

Promise.all  will reject as soon as one of the Promises in the array rejects or in details, it will run all your promises until one of the following conditions are met:

  • All of them resolve, which would, in turn, resolve the promise returned by the method
  • One of them fail, which would immediately reject the promise returned

When to Use: When you want results only when all the promises are resolved.

Promise.allSettled()

Promise.allSettled  will never reject – it will resolve once all Promises in the array have either rejected or resolved.

The output in Promise.allSettled is an array of object with 2 properties:

  1. status: The status of the returned promised (either ‘rejected’ or ‘fulfilled’)
  2. value/reason: The value of the fulfilled promise or the reason the in case of a rejected promise
{ status: "fulfilled", value: 3 }
{ status: "rejected", reason: "foo" }

When to Use: You should use Promise.allSettled when you want the response from all the promises whether they get resolved or rejected.

Let me know your thoughts

Theme by Anders Norén

%d bloggers like this:
Bitnami