Node.js · Chapter 31 of 43

Promises

A Promise represents a value that may not be available yet — it can be pending, fulfilled, or rejected. Promises are the foundation that async/await is built on.

Promises let you chain asynchronous operations with `.then()` and handle failures with `.catch()`, avoiding deeply nested callbacks.

Creating a promise

The `Promise` constructor takes a function with `resolve` and `reject` parameters, called when the async operation finishes.

Chaining promises

`.then()` returns a new Promise, letting you chain multiple asynchronous steps; `.catch()` handles any rejection in the chain.

Example 1 (javascript)
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
wait(1000).then(() => console.log('1 second passed'));
Output
1 second passed

The Promise resolves after the timeout, then .then() runs.

Example 2 (javascript)
fetchUser()
  .then(user => fetchPosts(user.id))
  .then(posts => console.log(posts))
  .catch(err => console.error(err));
Output
[...] or an error is logged

.then() chains dependent async steps; .catch() handles any failure along the chain.

Key points

  • A Promise can be pending, fulfilled, or rejected.
  • resolve()/reject() settle a Promise's outcome.
  • .then() chains follow-up actions; .catch() handles errors.
  • async/await is built on top of Promises.
💡 Note: Promise.all() runs multiple promises concurrently and waits for all to finish.

📝 Quick Quiz

1. What are the three states of a Promise?

2. Which method chains an action after a Promise resolves?

3. Which method handles Promise rejections?