Sikau

JavaScript · Day 52 · about 30 min

Promises

An order ticket.

Your order ticket

At a momo stall you get a token: "Number 42". It's a promise that you'll get food later — or bad news if they run out. A JavaScript promise is that token for a future value.

Using a promise: then and catch

function orderMomo() {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Momo ready! 🥟"), 500);
  });
}

orderMomo().then((food) => {
  console.log(food);
});
console.log("Token received, waiting…");

A promise can also fail. Call reject with an error, and handle it with .catch:

function orderMomo(plates) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (plates > 5) reject(new Error("Sorry, not enough momo!"));
      else resolve(plates + " plates ready");
    }, 300);
  });
}

orderMomo(10)
  .then((msg) => console.log(msg))
  .catch((err) => console.log("Problem: " + err.message));

The rest of this lesson

  • Chaining instead of nestingexplain
  • A promise's three statesexplain
  • Predict the outputpredict
  • Promise vocabularymatch
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript