Promises in JavaScript

Three States of Promises

  1. Pending - the Promise object has not resolved. Once it does, the state of the Promise object may transition to either the fulfilled or rejected state.
  2. Fulfilled - Whatever operation the Promise represented succeeded and your success handler will get called. Now that it’s fulfilled, the Promise:
  3. Rejected - Whatever operation the Promise represented failed and your error handler will get called. Now that it’s rejected, the Promise:

Promise Syntax

const myPromise = new Promise((resolve, reject) => {
  // resolve() // invoking resolve will change state from pending to resolved
  // reject() // invoking reject will change state from pending to rejected
});
myPromise
  .then((resolveArg) => {
    // resolveArg is the argument that gets passed into the resolve function in the promise
    // executed when promise is resolved
  }, (rejectArg) => {
    // rejectArg is the argument that gets passed into the reject function in the promise
    // executed when promise is rejected
  });
myPromise
  .then(() => 'hello world!')
  .then(() => 'after hello world');

Learning Objectives

  1. Instantiate a Promise object
  2. Use Promises to write more maintainable asynchronous code
  3. Use the fetch API to make Promise-based API calls