AI Hints
JavaScript · Lesson 82 of 138

Promises

A value from the future.

⏱ 2 min read▶ Video at 1:39:11🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A promise is an object that stands for a value you don't have yet. Like a ticket at a coffee shop. You get the ticket now, and later it turns into your coffee, or the news that they ran out.

Promises
From the video: Promises
  • A value you don't have yet
  • Like a coffee ticket
  • Coffee, or bad news

Three states

Every promise starts pending, which means the job is still running. Then it settles, once. Either it's fulfilled, with a value, or it's rejected, with an error. After that, it never changes.

  1. Pending
  2. Fulfilled (value)
  3. Rejected (error)
Three states
From the video: Three states

Making a promise

New promise takes a function with two arguments, resolve and reject. Call resolve with the value when the job succeeds, or reject with an error when it fails. Here we pretend to bake, and finish after a short wait. Then runs when the promise is fulfilled. Run it.

app.jsjavascript
function bake(item) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (item === "cake") resolve("Your cake is ready");
      else reject(new Error(`We can't bake ${item}`));
    }, 200);
  });
}

const ticket = bake("cake");
console.log("Is the ticket a promise?", ticket instanceof Promise);
ticket.then(message => console.log(message));
Output
Is the ticket a promise? true
Your cake is ready

Summary

A promise stands for a future value. It's pending, then fulfilled with a value, or rejected with an error. Next, using then and catch.

Key takeaways
  • Pending → settled
  • resolve / reject
  • Settles once
Next up: then and catch — using promises