Skip to content
Async JavaScriptChapter 33 / 47Intermediate4 min read

Promises

Learn JavaScript promises, including pending, fulfilled, and rejected states, then, catch, finally, Promise.all, allSettled, any, race, and withResolvers.

On this page

1. What are promises?

When you start an async job, like fetching data from a server, you do not get the result right away. A promise is like a receipt: empty for now, and later filled with a value or an error.

Every promise is in one of three states: pending, fulfilled, or rejected. Once it settles, its state never changes again.

2. Why does it matter?

With Callbacks, nesting keeps growing and errors must be handled separately at every level. Promises give you a flat chain and error handling in one place.

CallbacksPromises
Every step is nested insideA flat chain of then
An error check at every levelOne catch handles all errors
Hard to combine parallel workPromise.all and allSettled
A callback can run twiceA promise settles only once

3. Where is it used?

PlaceExample
Networkfetch(url) returns a promise
Files (Node.js)Methods from fs/promises
Parallel requestsPromise.all([getUser(), getPosts()])
TimeoutsGiving up on a slow request with Promise.race
async / awaitawait works on promises

4. How does it work?

The life of a promise
A new Promise is created, state pending
The work succeeds, resolve(value) and the state is fulfilled
Or the work fails, reject(error) and the state is rejected
The callbacks of then, catch, or finally run as microtasks
MethodWhen it runs
.then(fn)When fulfilled, with the value
.catch(fn)When rejected, with the error
.finally(fn)In both cases, for cleanup

5. Code example

Creating a promise and chaining

js
function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: "Sara" });
      else reject(new Error("User not found"));
    }, 300);
  });
}

getUser(1)
  .then((user) => user.name.toUpperCase())
  .then((name) => console.log(name))
  .catch((error) => console.error(error.message))
  .finally(() => console.log("Done"));

Combinators

js
const tasks = [getUser(1), getUser(-1), getUser(2)];

const all = await Promise.allSettled(tasks);
all.forEach((r) => console.log(r.status));

const first = await Promise.any(tasks);
console.log(first.name);

Promise.withResolvers

js
const { promise, resolve } = Promise.withResolvers();

button.addEventListener("click", () => resolve("clicked"), { once: true });

console.log(await promise);

How does the code work?

PartMeaning
Promise.allAn array if all are fulfilled, rejects immediately if even one rejects
Promise.allSettledWaits for all, gives each one's status and value or reason
Promise.anyThe first fulfilled, AggregateError if all fail
Promise.raceWhichever settles first, success or failure
Promise.withResolvers()The promise and its resolve, reject in separate variables

Interview tip

all vs allSettled is often asked. Use allSettled when you want every result even if some fail. Use all when one failure makes everything useless.

6. Common mistakes

Mistake: Forgetting return inside then

Why? The next then gets undefined and the chain breaks.

Better: Return a value or a promise from every then.

Mistake: Not adding a catch

Why? An unhandled promise rejection shows an error in the console and can stop the Node.js process.

Better: Add a catch at the end of every chain, or keep await inside try catch.

Mistake: Nesting promises inside then

Why? It brings callback hell back.

Better: Return the inner promise so the chain stays flat.

Mistake: Running independent requests one after another

Why? Three requests of 1 second each take 3 seconds.

Better: Run them in parallel with Promise.all, and the total time is the slowest request.

7. What to learn before and after

Suggested order
Callbacks
Promises
Async Await
Fetch API

Final quick revision

PointDetail
Statespending, fulfilled, rejected
then / catch / finallyResult, error, cleanup
ChainEvery then gives a new promise
all / allSettledAll together, fail fast vs a report on all
any / raceFirst success vs first to settle
withResolversFor resolving from outside