Curriculum / Advanced / Lesson 21

Promises

Handling asynchronous code with Promise objects.

21 of 30
advanced 📖 8 min read 🎯 4 questions

What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It's a way to handle asynchronous code without callback hell.

💡 Key insight A Promise is like a receipt at a restaurant. You get it immediately, but the food (the result) comes later. The receipt can be fulfilled (food arrives) or rejected (order canceled).

Promise States

Creating a Promise

const promise = new Promise((resolve, reject) => {
  // Asynchronous operation
  if (success) {
    resolve(result); // Fulfilled
  } else {
    reject(error); // Rejected
  }
});

Using Promises

// With .then() and .catch()
promise
  .then(result => console.log(result))
  .catch(error => console.error(error));

// With async/await (covered next lesson)
async function handlePromise() {
  try {
    const result = await promise;
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

Promise Chaining

Promises can be chained to run sequential async operations.

fetchUser()
  .then(user => fetchProfile(user.id))
  .then(profile => console.log(profile))
  .catch(error => console.error(error));

Promise Methods

Common Mistakes

Quick Quiz

1. What are the three states of a Promise?

2. Which method is used to handle a rejected promise?

3. What does Promise.all() do?

4. What happens if you don't call resolve() or reject()?

Summary

Back to curriculum