Promises

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

The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.

For example:

const myPromise = new Promise(function (resolve, reject) {
  let sampleData = [2, 4, 6, 8];
  let randomNumber = Math.floor(Math.random() * (sampleData.length + 1));
  if (sampleData[randomNumber]) {
    resolve(sampleData[randomNumber]);
  } else {
    reject('An error occured!');
  }
});

myPromise
  .then(function (e) {
    console.log(e);
  })
  .catch(function (error) {
    throw new Error(error);
  })
  .finally(function () {
    console.log('Promise completed');
  });

Methods

These methods are available on Promise.prototype

The .then() method takes up to two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each .then() returns a newly generated promise object, which can optionally be used for chaining.1

const promise1 = new Promise(function (resolve, reject) {
  resolve('Success!');
});

promise1.then(function (value) {
  console.log(value);
  // expected output: "Success!"
});


References

A .catch() is really just a .then() without a slot for a callback function for the case when the promise is resolved. It is used to handle rejected promises.2

const promise1 = new Promise((resolve, reject) => {
  throw 'An error occured';
});

promise1.catch(function (error) {
  console.error(error);
});
// expected output: An error occured

References


References


Children
  1. catch
  2. finally
  3. then