Javascript Promises

Arun Rajeevan
2 min readSep 9, 2019

--

A promise can be:

  • fulfilled — The action relating to the promise succeeded
  • rejected — The action relating to the promise failed
  • pending — Hasn’t fulfilled or rejected yet
  • settled — Has fulfilled or rejected

It heavily uses the chaining design pattern.

Promise.reject returns a new Promise object that is rejected with the given reason.

Promise.resolve returns a new Promise object that is resolved with the given value.

Promise.catch is rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback.

Promise.then can have both fulfillment and rejection handlers to the promise and returns a new promise resolving to the return value of the called handler. But usually, it is used to handle the fulfilled promise.

Promise.finally is a handler that returns a new promise and is called when the promise is settled, whether fulfilled or rejected.

Promise.race returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

Promise.all returns a single promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason for the first promise that rejects. There is no implied ordering in the execution of the array of Promises given. On some computers, they may be executed in parallel, or in some sense concurrently, while on others they may be executed serially. For this reason, there must be no dependency in any Promise on the order of execution of the Promises.

Promise.allSettled returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.

--

--

No responses yet