learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Promises

Objects that represent a value that will be available later, with then/catch chaining.

Promises explained

A promise is an object that stands for a value that is not ready yet. It starts pending and settles once, either fulfilled with a value or rejected with an error. You attach reactions with .then and .catch, and because every .then returns a new promise, steps chain in order instead of nesting callbacks.

How promises chain

fetch("/api/user")
  .then((res) => res.json())            // return a value or another promise
  .then((user) => fetch(`/api/orders/${user.id}`))
  .then((res) => res.json())
  .catch((err) => console.error(err))     // one place for any error above
  .finally(() => hideSpinner());

Whatever a .then callback returns becomes the value of the next promise. If it returns a promise, the chain waits for it. If anything throws, control jumps to the nearest .catch.

Running promises together

  • Promise.all: waits for all of them; rejects as soon as one rejects. Use it when you need every result.
  • Promise.allSettled: waits for all and reports each outcome. Use it when some failures are acceptable.
  • Promise.race: settles with the first one to settle, success or failure. Handy for timeouts.
  • Promise.any: fulfils with the first success; rejects only if all fail.

Common mistakes

  • Forgetting to return inside .then. The next step receives undefined and runs before the inner work finishes.
  • Nesting promises like callbacks instead of returning them and chaining.
  • Unhandled rejections: a chain with no .catch hides errors (and Node.js treats them as fatal by default).
  • Thinking promises are lazy. The work starts when the promise is created, not when you call .then.

What interviewers ask about promises

  • "What are the three states of a promise?" Pending, fulfilled, rejected; once settled it never changes.
  • "Promise.all versus allSettled?" Fail fast versus collect every outcome.
  • "Implement Promise.all." Keep a results array and a counter; resolve when the counter reaches the length; reject on the first error.
  • "When does a .then callback run?" As a microtask, after the current code finishes, never synchronously.
Concept map
Learn firstCallbacks
Part of JavaScriptPromises

What should you learn before Promises?

  1. FunctionsReusable blocks of code; in JavaScript they are values that can be passed around and returned.
  2. CallbacksPromises replaced nested callbacks.

What to learn after Promises

  • Async/awaitasync/await is syntax on top of promises.
  • Fetch APIThe standard way to make HTTP requests from JavaScript.

Connections to other concepts

Part of
JavaScript

Practise Promises

All topics