Promises

A value that will exist in the future. The foundation of modern async JavaScript.

Creating Promises

Wrap an async operation in a Promise.

const promise = new Promise((resolve, reject) => {
  // Do async work...
  const success = true;

  if (success) {
    resolve("It worked!"); // → fulfilled
  } else {
    reject(new Error("Failed")); // → rejected
  }
});

The Promise constructor takes an 'executor' function with resolve and reject. Call resolve for success, reject for failure.

1 / 3

then / catch / finally

Consuming promise results.

const promise = fetchData();

// .then() — runs on fulfillment:
promise.then(data => {
  console.log("Got:", data);
});

// .catch() — runs on rejection:
promise.catch(error => {
  console.error("Failed:", error.message);
});

// .finally() — runs ALWAYS (fulfilled or rejected):
promise.finally(() => {
  hideLoadingSpinner(); // cleanup
});

// Combined:
fetchData()
  .then(data => process(data))
  .catch(err => showError(err))
  .finally(() => hideSpinner());

.then()

on success

.catch()

on error

.finally()

always

Promise Chaining

Each .then() returns a new promise. Chain sequential operations.

fetch("/api/user")
  .then(response => response.json())    // returns Promise
  .then(user => fetch(`/api/posts/${user.id}`)) // returns Promise
  .then(response => response.json())    // returns Promise
  .then(posts => console.log(posts))    // final value
  .catch(err => console.error(err));    // catches ANY error above

Each .then() receives the resolved value of the previous promise. If you return a Promise, the next .then() waits for it.

1 / 3

Combinators

Orchestrate multiple promises running in parallel.

// Promise.all — wait for ALL to succeed
const [users, posts, comments] = await Promise.all([
  fetchUsers(),
  fetchPosts(),
  fetchComments()
]);
// All three run in parallel!
// Rejects immediately if ANY one fails

Runs all promises in parallel. Resolves with an array of all results. Fails fast — if any promise rejects, the whole thing rejects.

💡 Fail fast: one failure = total failure
1 / 4

Microtask Queue

Promise callbacks run before setTimeout callbacks.

console.log("1. sync");

setTimeout(() => console.log("4. macrotask"), 0);

Promise.resolve().then(() => console.log("3. microtask"));

console.log("2. sync");

// Output order:
// "1. sync"
// "2. sync"
// "3. microtask"   ← Promise.then (microtask queue)
// "4. macrotask"   ← setTimeout (macrotask queue)

Execution priority:

1. Synchronous code (call stack)

2. Microtasks (.then, .catch, .finally, queueMicrotask)

3. Macrotasks (setTimeout, setInterval, I/O)

FAQ

Common questions about Promises.