Promises

The "Promise" construct was added to JavaScript in ES6. It was meant to address some of the issues with asynchronous coding, including the callback hell.

A "Promise" is a JavaScript object that holds the eventual result of an asynchronous operation.

A "promise" object has a "state," and its state at any point in time is one of the following:

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

A Promise is in the "pending state" as soon as it is created to kick off some asynchronous operation. Once the asynchronous process is completed, the Promise is fulfilled. However, suppose for any reason, the asynchronous operations fail (for example, the network connection is disrupted in the middle of an HTTP request). In that case, the Promise is rejected.

This is the general pattern for creating a Promise object:

const myPromise = new Promise((resolve, reject) => {
  let result = [];
  let success = false;
  // Do some async work!
  //  The success and result variables
  //  must be updated through this work.

  if (success) {
    resolve(result);
  } else {
    reject(new Error("some message!"));
  }
});

Note that the constructor of Promise takes in a function that takes two (callback) functions, resolve and reject, as arguments.

Here is how you would consume a promise:

myPromise
  .then((result) => {
    /* do something with result */
  })
  .catch((error) => {
    /* display the error or otherwise handle it */
  });

Notice you had seen this pattern before when we used the fetch API.

Resources