Promises

What is a Promise?

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

Example

const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

delay(50, "data loaded").then((result) => console.log(result));
console.log("promise created, waiting...");

Output

promise created, waiting...
data loaded

Chaining and Errors

Example

Each .then returns a new promise, so steps chain flatly. One .catch handles an error from any step:

const delay = (ms, v) => new Promise((res) => setTimeout(() => res(v), ms));

delay(20, 5)
  .then((n) => n * 2)
  .then((n) => {
    if (n > 5) throw new Error("Too big: " + n);
    return n;
  })
  .then((n) => console.log("never runs", n))
  .catch((err) => console.log("Caught:", err.message))
  .finally(() => console.log("cleanup"));

Output

Caught: Too big: 10
cleanup