Thuta Learning
JavaScript
AdvancedProgrammingBeginner

JS Promises

JavaScriptLesson 3430 min

What you'll walk away with

  • Create a Promise with new Promise((resolve, reject) => ...) and name its three states
  • Predict how a value returned or an error thrown inside then travels down the chain
  • Show with output order that then callbacks run after the current synchronous code
  • Choose between Promise.all and Promise.allSettled for several independent jobs

Explain it simply

Promises in plain language

A Promise is an object that stands for a result you do not have yet. Reading a file, sending a request to a server or waiting for a timer cannot hand you an answer immediately. Instead they hand you a Promise right away, which says: when I finish, I will give you either a value or an error.

Think of the numbered buzzer a restaurant gives you. The buzzer is not food, but it guarantees you will later get either your meal or a message that the dish is sold out. You can do other things while you wait, and when the result arrives, .then() handles the success value and .catch() handles the error.

Problem → Why → Solution

The problem: a chain that finishes too early

You want to load a user, then load that user's orders, then log 'done'. The code below looks right, yet 'done' prints before the orders arrive and the second then receives undefined. If loading the orders fails, the catch never sees it and you get an unhandled rejection instead.

broken-chain.js
loadUser(7)
  .then((user) => {
    loadOrders(user.id); // starts the work but does not return it
  })
  .then((orders) => {
    console.log(orders); // undefined
    console.log("done"); // runs before the orders have loaded
  })
  .catch((error) => console.error(error)); // never sees a loadOrders failure

Why this happens

Every then returns a new Promise that settles with whatever its callback returns. A callback that returns nothing fulfils immediately with undefined, so the chain moves on. Only when you return the Promise from loadOrders does the chain wait for it and route its error to the catch.

Core concept: an object that settles once and chains

A Promise has three states: pending (still waiting), fulfilled (succeeded with a value) and rejected (failed with a reason). It moves from pending to one of the other two exactly once, and after it has settled it never changes again. Calling resolve twice, or reject after resolve, is silently ignored.

The executor function you pass to new Promise runs immediately and synchronously. Inside it you start the work and later call resolve(value) or reject(error). Prefer rejecting with an Error object rather than a plain string: you get a stack trace, and every handler can read error.message the same way.

then, catch and finally each return a new Promise, which is why they chain. If a callback returns a plain value, the next step receives that value. If it returns a Promise, the chain waits for it to settle. If it throws, or returns a rejected Promise, control skips the following then handlers and lands in the nearest catch. A catch that returns a value puts the chain back on the success path.

Even when a Promise is already settled, then callbacks run only after the current synchronous code has finished, from the microtask queue. That is why a console.log placed after Promise.resolve(1).then(log) prints first. Promises also have no built-in cancellation, so APIs such as fetch use a separate AbortController for that.

CombinatorWhen it settles
Promise.allall fulfil: array of values; any rejects: rejects at once
Promise.allSettledalways fulfils, after all finish, with { status, value | reason }
Promise.racecopies the first Promise to settle, success or failure
Promise.anyfirst fulfilment; AggregateError if every one rejects
A Promise as a one-time delivery slip
  1. Start work, get a pending slip now
  2. resolve or reject happens only once
  3. then/catch run after the sync code
  4. A returned value feeds the next then
  5. A throw jumps to the nearest catch

If a then callback starts async work, always return that Promise; otherwise the chain will not wait for it.

General pattern

javascript
const promise = new Promise((resolve, reject) => {
  // start the work; later call resolve(value) or reject(new Error(msg))
});

promise
  .then((value) => nextValueOrPromise)
  .catch((error) => fallbackValue)
  .finally(() => cleanup());

Promise.all([taskA(), taskB()]).then(([a, b]) => use(a, b));

Start the work in the executor and settle it once. What a then callback returns becomes the next step's input, catch handles an error from any step above it, and finally is for cleanup without changing the value.

Worked example: creating and consuming a Promise

This example builds a Promise by hand and resolves it straight away. Try changing success to false: then is skipped and catch runs instead. It shows that a Promise has two exits, a success path and a failure path, and settling picks exactly one of them.

javascript
const myPromise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("The operation was successful!");
  } else {
    reject("The operation failed.");
  }
});

myPromise
  .then((message) => {
    console.log(message);
  })
  .catch((error) => {
    console.error(error);
  });

Code breakdown

  1. Create the Promiseconst myPromise = new Promise((resolve, reject) => {

    The executor runs immediately and receives two functions, resolve and reject. At this moment myPromise is still pending.

  2. Fulfil itresolve("The operation was successful!");

    Calling resolve fulfils the Promise with this string; any later resolve or reject call is ignored.

  3. The failure pathreject("The operation failed.");

    This line runs only when success is false. In real code prefer reject(new Error("The operation failed.")) so handlers get a proper Error.

  4. Handle success.then((message) => {

    The fulfilled value arrives as message. This callback runs only after the synchronous part of the script has finished.

  5. Handle failure.catch((error) => {

    This catch runs if the Promise rejects or if the then callback throws. In this run it is never called.

You should see
The operation was successful!

How values and errors flow through a chain

Before running the code below, predict the order of the lines. The numbers show the real order. Both synchronous logs come first, the length returned by the first then reaches the second, the throw skips the third then and lands in catch, and finally always runs last.

chain-order.js
console.log("1: synchronous code runs first");

Promise.resolve("ready")
  .then((value) => {
    console.log("3: then received", value);
    return value.length; // a plain value becomes the next step's input
  })
  .then((length) => {
    console.log("4: next then received", length);
    throw new Error("disk full");
  })
  .then(() => console.log("skipped: a rejection jumps over this"))
  .catch((error) => console.log("5: catch received", error.message))
  .finally(() => console.log("6: finally runs either way"));

console.log("2: still synchronous");

Check the output yourself

It prints 1, 2, 3 (ready), 4 (5), 5 (disk full), 6. The "skipped" line never appears.

In real projects

Promises in real projects

Most asynchronous APIs in modern JavaScript return Promises: fetch in browsers and Node, Node's fs/promises module, most database drivers, and every async function. Understanding Promises is therefore the foundation for all of them, and async/await, covered in the next lesson, is built directly on top of them.

  • A dashboard loads profile and settings at the same time with Promise.all, because they do not depend on each other, and shows an error page if either fails since both are required.
  • Optional widgets such as ads or recommendations use Promise.allSettled, so one failing widget is simply hidden while the rest still render.
  • A loading spinner is turned off inside finally, so it never keeps spinning after either a success or an error.
  • Older callback-style APIs are wrapped with new Promise, or with util.promisify in Node, so the whole codebase speaks one Promise style. You simply route the error-first callback's err to reject and its result to resolve.

Common mistakes

Common mistakes with Promises

Not returning the inner Promise from then

then((user) => { loadOrders(user.id); }) starts the work but the chain does not wait: the next step gets undefined and a loadOrders failure never reaches catch. Write return loadOrders(user.id), or use an arrow function without curly braces.

Leaving a chain without a catch

When nobody handles a rejection, browsers log Uncaught (in promise) in the console and current Node.js versions terminate the process by default. End every chain with a catch, or return it to a caller who will handle it.

Using Promise.all where partial failure is acceptable

Promise.all rejects as soon as one input rejects, and you lose the values that did succeed. Use Promise.allSettled when you need each outcome separately. Note that Promise.all does not stop the other jobs either; they keep running in the background.

Best practices

Best practices

  • Reject with new Error(...), not with a bare string.
  • Keep chains flat: return the Promise instead of nesting then inside then.
  • Start independent jobs first, then wait for them together with Promise.all.
  • Put cleanup such as hiding a spinner or closing a connection in finally.

Mini challenge

Mini challenge: a dashboard loader

Coordinate three fake services built on timers: profile, settings and ads. Load profile and settings together and print a one-line summary. Then try settings and ads with Promise.all, catch the failure, and continue with an allSettled report.

  • delay(ms, value) resolves with value after ms milliseconds
  • failAfter(ms, message) rejects with an Error after ms milliseconds
  • loadDashboard uses Promise.all and resolves with a summary string
  • loadEverything maps allSettled results to "ok" or "failed: ..."
  • Connect the steps in one flat chain with correct returns, no nested then
dashboard.js
function delay(ms, value) {
  // TODO: return a Promise that resolves with value after ms (use setTimeout)
}

function failAfter(ms, message) {
  // TODO: return a Promise that rejects with new Error(message) after ms
}

const loadProfile = () => delay(30, { name: "Aung Kyaw" });
const loadSettings = () => delay(10, { theme: "dark" });
const loadAds = () => failAfter(20, "ads service down");

function loadDashboard() {
  // TODO: run loadProfile and loadSettings together,
  // resolve with "<name> uses the <theme> theme"
}

function loadEverything() {
  // TODO: Promise.allSettled for profile + ads, map each result to
  // "ok" or "failed: <message>"
}

// TODO: one flat chain:
// 1. print "all:" + loadDashboard() result
// 2. return Promise.all([loadSettings(), loadAds()])
// 3. catch: print "all rejected:" + message, return loadEverything()
// 4. print "allSettled:" + the report

Expected: Three lines in this order: all: Aung Kyaw uses the dark theme, all rejected: ads service down, allSettled: [ 'ok', 'failed: ads service down' ].

Show hint

Destructure the Promise.all result as ([profile, settings]) => .... Each allSettled entry has status "fulfilled" or "rejected"; for a rejection read reason.message.

Show solution
dashboard.js
function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

function failAfter(ms, message) {
  return new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
}

const loadProfile = () => delay(30, { name: "Aung Kyaw" });
const loadSettings = () => delay(10, { theme: "dark" });
const loadAds = () => failAfter(20, "ads service down");

function loadDashboard() {
  return Promise.all([loadProfile(), loadSettings()]).then(([profile, settings]) => {
    return `${profile.name} uses the ${settings.theme} theme`;
  });
}

function loadEverything() {
  return Promise.allSettled([loadProfile(), loadAds()]).then((results) =>
    results.map((r) => (r.status === "fulfilled" ? "ok" : `failed: ${r.reason.message}`)),
  );
}

loadDashboard()
  .then((summary) => {
    console.log("all:", summary);
    return Promise.all([loadSettings(), loadAds()]);
  })
  .catch((error) => {
    console.log("all rejected:", error.message);
    return loadEverything();
  })
  .then((report) => console.log("allSettled:", report));

Quick quiz 1 / 3

What does this print? console.log("A"); Promise.resolve().then(() => console.log("B")); console.log("C");

Quick quiz 2 / 3

What does Promise.resolve(2).then((n) => n * 10).then((n) => console.log(n)) print?

Quick quiz 3 / 3

A page loads three optional widgets and should hide only the ones that fail. Which fits best?

What to remember

  • A Promise settles once, from pending to fulfilled or rejected, and never changes after that.
  • then, catch and finally each return a new Promise: returned values move forward, throws jump to the nearest catch.
  • then callbacks run only after the current synchronous code has finished.
  • Use Promise.all when every result is required and Promise.allSettled when you need each outcome.

MDN — Asynchronous JavaScript — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Promises | Thuta Learning