Skip to content
Kuza Ndoto Academy

Promises

Beginner → IntermediateChapter 5 · Page 23 of 324 min readUpdated 15 Nov 2026

A promise is an object that stands for a value you don't have yet: an API reply, a file, a payment confirmation. Instead of passing callbacks into a function, the function hands you a promise, and you attach what should happen when it succeeds or fails. Promises are the foundation of fetch and async/await.

The three states

A promise is always in one of three states:

  • pending: the work is still going on;
  • fulfilled: it finished successfully and has a value;
  • rejected: it failed and has a reason (usually an Error).

Once a promise is fulfilled or rejected it is settled, and it never changes again.

pendingstill working fulfilledhas a value rejectedhas a reason (error) .then(value => ...) .catch(error => ...) resolve(v) reject(e) .finally() runs either way Once settled, a promise never changes state again
Figure 1. A promise starts pending and settles exactly once. then handles the value, catch handles the error and finally runs after either.

Creating a promise

You create one with new Promise(executor). The executor function receives two functions: call resolve(value) on success or reject(error) on failure. Here we pretend to check an M-Pesa balance, using setTimeout to simulate the network delay:

function checkBalance(amount) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (amount <= 500) {
        resolve(`Approved: KES ${amount}`);
      } else {
        reject(new Error("Insufficient balance"));
      }
    }, 1000);
  });
}

checkBalance(300)
  .then((message) => console.log(message))
  .catch((error) => console.log(error.message))
  .finally(() => console.log("Done"));

checkBalance(800)
  .then((message) => console.log(message))
  .catch((error) => console.log(error.message))
  .finally(() => console.log("Done"));
Approved: KES 300 Done Insufficient balance Done

After one second, the first timer resolves its promise, and all of that promise's callbacks run as microtasks before the second timer fires. Most of the time you won't create promises yourself; you will consume promises returned by functions like fetch. Still, building one shows what is happening inside.

then, catch and finally

  • .then(onFulfilled) runs with the value when the promise fulfils.
  • .catch(onRejected) runs with the reason when it rejects.
  • .finally(onSettled) runs either way, with no argument. It is ideal for clean-up such as hiding a loading spinner.

Each of these returns a new promise, which is what makes chaining possible.

Chaining

Whatever a .then callback returns becomes the value for the next .then. If it returns another promise, the chain waits for that promise first. This turns nested callbacks into a flat, readable sequence.

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

Promise.resolve(2)
  .then((n) => n * 10)                         // 20
  .then((n) => wait(500).then(() => n + 5))    // waits, then 25
  .then((n) => console.log(n));
25

If any step throws an error or returns a rejected promise, the chain skips the remaining .then callbacks and jumps to the nearest .catch:

Promise.resolve("42")
  .then((text) => JSON.parse(text))
  .then((n) => {
    throw new Error(`Bad value ${n}`);
  })
  .then(() => console.log("never runs"))
  .catch((error) => console.log("Caught:", error.message));
Caught: Bad value 42
Common mistake

Forgetting to return inside a .then that uses curly braces. .then((n) => { wait(500); n + 5; }) returns undefined, so the next step receives undefined immediately without waiting. Arrow functions without braces return automatically; with braces you must write return.

Running promises together

To wait for several independent jobs at once, use the built-in combinators. These examples use two helpers:

const after = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

Promise.all waits for all of them and gives an array of values in the original order, no matter which finished first:

Promise.all([after(300, "rice"), after(100, "beans")])
  .then((values) => console.log(values));
['rice', 'beans']

But if any one rejects, Promise.all rejects straight away with that error:

Promise.all([after(300, "rice"), failAfter(100, "No beans")])
  .then((values) => console.log(values))
  .catch((error) => console.log("Failed:", error.message));
Failed: No beans

Promise.allSettled never rejects. It waits for every promise and reports each outcome:

Promise.allSettled([after(100, "rice"), failAfter(200, "No beans")])
  .then((results) => results.forEach((r) => console.log(r.status, r.value ?? r.reason.message)));
fulfilled rice rejected No beans

Promise.race settles as soon as the first promise settles, which is handy for timeouts. Promise.any waits for the first one to fulfil, ignoring failures unless all fail.

Promise.race([after(300, "slow matatu"), after(100, "fast boda")])
  .then((winner) => console.log(winner));
fast boda
MethodFulfils whenRejects when
Promise.allall fulfil (array of values)any one rejects
Promise.allSettledall settle (array of results)never
Promise.racethe first to settle fulfilsthe first to settle rejects
Promise.anythe first one fulfilsall reject
Warning

Always end a chain with .catch (or use try/catch with await). A rejected promise with no handler produces an "Uncaught (in promise)" error in the console, and your user sees nothing helpful.

Key points

  • A promise is pending, then settles once as fulfilled (with a value) or rejected (with a reason).
  • .then, .catch and .finally each return a new promise, so you can chain them.
  • Return values flow down the chain; a thrown error jumps to the next .catch.
  • Use Promise.all for "all must succeed", allSettled for "tell me every result" and race/any for "first one wins".
Up next · Asynchronous JavaScriptAsync & AwaitWrite asynchronous code that reads top to bottom.
→

Tip: use the ← and → keys to move between pages.