JavaScript Tutorial · Asynchronous JavaScript · Lesson 32 of 44

JavaScript Promises

Create and chain promises, handle errors and run tasks in parallel.

What is a promise?

A Promise represents a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error.

Example 1Try it yourself
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const p = wait(100, "data loaded");
console.log(p);
p.then((value) => console.log(value));

Output

Promise { <pending> }
data loaded

Chaining

then() returns a new promise, so steps chain without nesting. One catch() at the end handles an error from any step; finally() runs either way:

Example 2Try it yourself
const getUser = (id) => Promise.resolve({ id, name: "Ada" });
const getOrders = (user) =>
  user.id === 1 ? Promise.resolve(["book", "pen"]) : Promise.reject(new Error("no orders"));

getUser(1)
  .then((user) => getOrders(user))
  .then((orders) => console.log("orders:", orders))
  .catch((err) => console.log("failed:", err.message))
  .finally(() => console.log("done 1"));

getUser(2)
  .then(getOrders)
  .then((orders) => console.log("orders:", orders))
  .catch((err) => console.log("failed:", err.message));

Output

orders: [ 'book', 'pen' ]
failed: no orders
done 1

Running promises together

  • Promise.all([...]) — wait for all; rejects if any fails.
  • Promise.allSettled([...]) — wait for all and report each result.
  • Promise.race([...]) / Promise.any([...]) — first to settle / first to succeed.
Example 3Try it yourself
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms));

Promise.all([wait(50, "a"), wait(10, "b")]).then((v) => console.log("all:", v));
Promise.allSettled([wait(10, "ok"), fail(20)]).then((results) =>
  console.log("settled:", results.map((r) => r.status)));
Promise.race([wait(30, "slow"), wait(5, "fast")]).then((v) => console.log("race:", v));

Output

race: fast
settled: [ 'fulfilled', 'rejected' ]
all: [ 'a', 'b' ]

Test yourself

Which method waits for every promise and never rejects?

  1. Promise.all()
  2. Promise.race()
  3. Promise.allSettled()
  4. Promise.any()
Show answer

Answer: Promise.allSettled()