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:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e not fulfilled or rejected yet
- 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: –
- Promise.all()
- Promise.allSettled()
Short Circuit when | Fulfilled when | Rejected When | |
---|---|---|---|
Promise.all | 1st promise rejected | All fulfilled promises | 1st promise rejected |
Promise.allSettled() | Not allowed | Always | Never 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:
- status: The status of the returned promised (either ‘rejected’ or ‘fulfilled’)
- 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