Javascript: Promise Class methods (all, allSettled, race)

Ravina Deogadkar - Apr 14 '20 - - Dev Community

Hi everyone! It's just another week with all the days feeling similar as such. With time passing by observing and learning lots of new languages and technologies. Along with that strengthening, the core is much more important. Unless you make your base strong you won't be able to build higher. Let's make our Javascript base stronger with another core concept Promise.

Promise

A promise is an object that represents an eventual execution of an asynchronous function and its resulting value. A promise is an asynchronous method returning values like synchronous methods.

The promise is in one of the following states.

  • Pending: initial state
  • Rejected: operation failed
  • Fulfilled: operation completed successfully

Like most of the other javascript objects Promise can be chained. Promise provides Promise.then(), Promise.catch() and Promise.finally() methods for handling exception condition.

As we are now aware of the Promise now let's look at some of the Promise methods.

Promise.all([promise1, promise2,...])

This method accepts an array of promises and waits until all of the passed promises is resolved or until the first promise is rejected. It returns an array of responses or reasons for rejection.

Alt Text

If all the promises are fulfilled then, the array of results of all fulfilled promises are returned.
If at least one promise fails then, the reason for rejection of the first promise is returned.

Promise.allSettled([promise1, promise2,...])

This method accepts an array of promises and waits until all of the passed promises are settled no matter whether they are resolved or rejected.

Alt Text

It returns an array of responses from all resolved promise or reasons for rejection along with Status.

For resolved promise object containing status as "fulfilled" along with the values are returned.

Alt Text

For rejected promise object containing status as "rejected" along with the reasons for rejection are returned.

Alt Text

allSettled() function do not need a catch() function for handling the rejected Promise. Since the allSettled() function waits for settlement of Promises and not the resolution or rejection of Promise.

Promise.race([promise1, promise2,...])

This method accepts an array of promises as input and returns the response from the first promise settled.

If the first promise to be settled is resolved then it returns data else it returns reason for rejection.

Alt Text

That's all for promise methods.

Happy Coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .