Skip to content
Codewilds

Lesson 31 of 34 · Async JavaScript

JavaScript Promises: then, catch and Chaining

medium20 XP3 min read

Callbacks work for a single "do this later", but real tasks come in sequences: load the player, then load their inventory, then render the screen, and handle errors at every step. Nesting callbacks inside callbacks quickly becomes unreadable.

Promises are JavaScript's answer. A promise is an object that represents a value you'll get in the future, and they're the foundation of fetch, async/await and almost every modern JavaScript API.

What is a promise?

A promise is like an order ticket at a tavern. You don't have your meal yet, but you have a ticket that will eventually turn into either a meal or an apology. A promise is always in one of three states:

  • pending: still waiting;
  • fulfilled: finished successfully, with a value;
  • rejected: failed, with a reason (usually an Error).

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

Creating a promise

You create a promise with new Promise, passing a function that receives two callbacks: call resolve(value) on success or reject(error) on failure:

function rollDice() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const roll = Math.floor(Math.random() * 6) + 1;
      if (roll === 1) {
        reject(new Error("Critical failure!"));
      } else {
        resolve(roll);
      }
    }, 500);
  });
}

For values you already have, Promise.resolve(value) and Promise.reject(error) create settled promises instantly.

Using a promise: then, catch and finally

You don't read a promise's value directly. You register callbacks:

rollDice()
  .then((roll) => console.log(`You rolled ${roll}`))
  .catch((error) => console.log(`Oops: ${error.message}`))
  .finally(() => console.log("Turn over"));
  • .then(callback) runs when the promise is fulfilled and receives the value.
  • .catch(callback) runs when it's rejected and receives the error.
  • .finally(callback) runs either way, which makes it perfect for cleanup.

Chaining

Here's the real power: .then() returns a new promise that resolves to whatever your callback returns. If the callback returns another promise, the chain waits for it. That turns nested callbacks into a flat, readable sequence. Imagine that loadPlayer and loadInventory both return promises:

loadPlayer(7)
  .then((player) => loadInventory(player.id)) // returns a promise: the chain waits
  .then((inventory) => inventory.length)      // returns a plain value
  .then((count) => console.log(`${count} items`))
  .catch((error) => console.log("Loading failed:", error.message));

Errors travel down the chain: if any step rejects or throws, the following then callbacks are skipped and the nearest catch handles it. A catch can also recover by returning a fallback value, after which the chain continues normally.

Common mistakes

  • Forgetting to return inside then. .then((p) => { loadInventory(p.id); }) doesn't wait for the inventory and passes undefined along.
  • Never handling rejections. Always end a chain with .catch(...). Otherwise the error goes unhandled: browsers report an "Uncaught (in promise)" error and Node.js crashes.
  • Wrapping a promise in new Promise for no reason. If a function already returns a promise, just return it or chain on it.
  • Expecting the value synchronously. const x = rollDice(); gives you the promise object, not the number.

Assignment

Write three promise-based functions. Use .then()/.catch() chains, not async/await (that's the next lesson).

  1. delay(ms, value) returns a promise that resolves with value after ms milliseconds.
  2. brewPotion(ingredients) returns a promise that settles after about 50 ms:
    • if ingredients is an empty array, it rejects with an Error whose message is "No ingredients";
    • otherwise it resolves with "Potion of " followed by the ingredients joined with " and ", for example "Potion of moss and ember".
  3. getLevel(fetchXp) receives a function fetchXp that returns a promise of an XP number. It returns a promise of the player's level, Math.floor(xp / 100) + 1. If fetchXp's promise rejects, the level falls back to 1.
delay(100, "done").then((v) => console.log(v)); // "done" after 0.1 s
brewPotion(["moss", "ember"]).then(console.log); // Potion of moss and ember
getLevel(() => Promise.resolve(250)).then(console.log); // 3

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 31 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.