Promises in Js

·

2 min read

Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

  • A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called.

As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.

Promise.race([P1,P2])

  • It cares only for for the fastest resolving promise.
  • In this an array of Promises is Provided as argument and this race() function would executed it's them block for the fastest resolving promise and it ignores rest all .

Promise.all([P1,P2])

  • It gives the resolved data of all promises combined in an array in the order of argument as in input array .
  • If any one of the Promises fails then ,this will result in the error and no further promises would be executed.
  • It waits for All settled or atleast one failed.

Promise.allSettled()

  • It will return the output of all promises (failed/succeeded both)in an array of objets combined.
  • It's different from the Promise.all() since the Promise.all() gives the result if all promises are resolved.