Lesson 73 +20 XP

Promises

Promises

A Promise is an object that represents a value that will be available later: success or failure.

The three states

  • pending: waiting for the result.
  • fulfilled: it worked, here is the value.
  • rejected: it failed, here is the error.

Creating a promise

const myPromise = new Promise(function(resolve, reject) {
  let success = true;
  if (success) {
    resolve("It worked!");
  } else {
    reject("It failed");
  }
});

Using a promise with .then

myPromise
  .then(function(result) {
    console.log(result); // success value
  })
  .catch(function(error) {
    console.log(error); // failure reason
  });

Chaining

.then calls can be chained, each receiving the previous result:

fetchSomething()
  .then(step1)
  .then(step2)
  .catch(handleError);

Promise.all

Wait for several promises together:

Promise.all([p1, p2]).then(function(values) {
  console.log(values); // both results
});

TL;DR

  • A Promise is a future value.
  • States: pending, fulfilled, rejected.
  • .then handles success, .catch handles errors.
  • Chains and Promise.all combine async work.