Promise Objects in JS: Easy as pie!

Navid Mostafiz
2 min readApr 23, 2018
  1. A Promise object provides some data or some error some time in the future based on the outcome of an asynchronous operation.
  2. The Promise Object takes an Executor Function inside which we perform some asynchronous operation
  3. The Promise Object also provides some Handler Functions such as:
  • then(): to receive & handle Resolved Data in case of success
  • catch(): to receive & handle Error Object in case of failure
  • finally(): to perform any final task after then/catch is completed
PC: pexel.com

Creating a Promise Object:

const promiseObj = new Promise(executor);

States of a Promise Object:

Fulfilled / Rejected / Pending

Executor Function: The Executor function launches the asynchronous operation. The Promise Object is in pending State at this point.

  • If the operation succeeds: It calls Promise.resolve(resolved_data) & changes the Promise State to Fulfilled & triggers the then() Handler function.
  • If the operation fails: It calls the Promise.reject(error_object) & changes the Promise State to Rejected & triggers catch() Handler function.

Handler Functions: So we see that Handler functions are triggered based on the outcome of the asynchronous operation. We provide Callback functions to these Handler functions to capture the data or error object and use them for our purpose.

promiseObj.then((data)=>{ console.log(data); });
promiseObj.catch((error)=>{ console.error(error); });

Promise Object Errors & Exceptions: All errors & exceptions are caught by catch() Handler function of the promise object, so no need to use try…catch block.

Flow diagram for both Fulfillment & Reject states:

Flow Diagram (Credits: Navid…me actually)

A sample executor function:

//The executor function
const promise = new Promise((resolve, reject) => {
//AN ASYNCHRONOUS CALL
const request = new XMLHttpRequest();
request.open(‘GET’, ‘https://api.com/get');
//ON SUCCESS
request.onload(() => {
if (request.status === 200) {
Promise.resolve(request.response);
});
//ON FAILURE
request.onerror(() => {
Promise.reject(Error(‘Error fetching data.’));
});
});

Chained Promises
If the callback function provided to a PROMISE Handler returns another promise Object, then it can be chained with more handler functions

myPromise
.then(CB1ThatAlsoReturnsAnotherPromiseObj)
.then(CB2ThatAlsoReturnsAnotherPromiseObj)
.then(CB3ThatAlsoReturnsAnotherPromiseObj)
.catch(CBThatCatchesErrorFromAnyAbovePromises)
.finally(CBToHandleAnyFinalOperations);

More Promise Object Functions:
* Promise.any(): returns the first Resolved Promise object.
* Promise.all(): Returns an array of all Resolved Promise objects after all of them are resolved or the first Rejected Promise object.
* Promise.race(): …will write this later … 😛

Hope this clarifies the concept of Promise Object in Javascript!!

--

--