JavaScript · Chapter 50 of 55

JavaScript Promises

A Promise represents a value that may not be available yet — the eventual result of an asynchronous operation. A Promise is always in one of three states: pending, fulfilled, or rejected.

You handle a Promise's outcome with `.then()` for success and `.catch()` for errors, optionally chaining multiple `.then()` calls together.

Creating and consuming

`new Promise((resolve, reject) => {...})` wraps async work. Consumers use `.then(value => ...)` and `.catch(error => ...)` to react to the outcome.

Chaining

Each `.then()` returns a new Promise, allowing you to chain multiple asynchronous steps in sequence, avoiding deeply nested callbacks.

Example 1 (javascript)
let promise = new Promise((resolve, reject) => {
  resolve("Success!");
});
promise.then(result => console.log(result));
Output
Success!

The Promise resolves immediately, triggering the .then() handler.

Example 2 (javascript)
function fetchData() {
  return new Promise(resolve => resolve(42));
}
fetchData()
  .then(data => data * 2)
  .then(result => console.log(result));
Output
84

Each .then() passes its return value to the next, forming a chain.

Key points

  • A Promise represents a future value: pending, fulfilled, or rejected.
  • .then() handles success, .catch() handles errors.
  • Promises can be chained since .then() returns a new Promise.
  • Promises avoid deeply nested callback structures.
💡 Note: Promise.all() lets you run multiple promises in parallel and wait for all to complete.

📝 Quick Quiz

1. What are the three states of a Promise?

2. Which method handles a successful Promise result?

3. Which method handles Promise errors?