Lesson 6, by Codesarray, , 8 min read

JavaScript promises and async/await: then, catch, Promise.all

Learn JavaScript promises and async await: the event loop in one picture, then/catch/finally chains, async functions with try/catch, Promise.all against sequential awaits, fetch, and ES2026's Array.fromAsync.

JavaScript promises and async await make sense the moment you see what fetch actually hands you: not your data, but Promise { <pending> } — an IOU. This page explains the machinery behind that IOU: the event loop in one picture, callbacks and why they pyramid, promises with then, catch and finally, async/await with ordinary try/catch, the combinators Promise.all, allSettled, any, race and try, and finally fetch and ES2026's Array.fromAsync. Everything here ran on Node 24, including the timings.

The event loop: how JavaScript waits without freezing

JavaScript runs your code on a single thread — one cook, in one kitchen, doing one thing at a time. If the cook stood staring at a pasta pot for ten minutes, the whole kitchen would freeze. So JavaScript never waits: slow things (timers, file reads, network requests) run off to the side, and when one finishes, its callback joins a queue. Whenever the call stack is free, the event loop hands the cook the next callback.

function step(name, ms, onDone) {
  setTimeout(() => {
    console.log(name, "done");
    onDone();
  }, ms);
}

console.log("Start dinner");
step("Boil pasta", 300, () => {
  step("Make sauce", 200, () => {
    step("Serve", 100, () => {
      console.log("Dinner is ready");
    });
  });
});
console.log("Chop the salad while waiting");
Start dinner
Chop the salad while waiting
Boil pasta done
Make sauce done
Serve done
Dinner is ready

The last line of code prints second, because the cook never stands still. That part is beautiful. The shape of the code is not: each step hides inside the previous step's callback, pushing the code further right. Three steps is readable; ten is the pyramid of doom.

Promises: then, catch, finally

A promise is a restaurant buzzer: not your food, a placeholder for food that is coming. It is an object in one of three states — pending, fulfilled (your value is ready) or rejected (here is the error) — and once it settles, it never changes again. You attach what happens next: .then runs on the value, .catch runs on a failure, .finally runs either way. The trick that kills the pyramid is that then returns a new promise, so returning the next step from inside a then chains them flat:

function step(name, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(name + " done"), ms);
  });
}

function dropThePlate(ms) {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error("the plate broke")), ms);
  });
}

const p = step("Boil pasta", 300);
console.log(p);

p.then((msg) => {
    console.log(msg);
    return step("Make sauce", 200);
  })
  .then((msg) => {
    console.log(msg);
    return dropThePlate(100);
  })
  .then(() => console.log("Serve done"))
  .catch((err) => console.log("Caught:", err.message))
  .finally(() => console.log("Kitchen closed"));
Promise { <pending> }
Boil pasta done
Make sauce done
Caught: the plate broke
Kitchen closed

Note what the rejection did: "Serve done" never printed. A rejected promise skips every remaining then and jumps to the nearest catch, so one catch at the end handles a failure anywhere in the chain. finally ran regardless.

async/await: a pause button for promises

async/await is the same machinery with better syntax. Put async before a function and you may use await inside it: await takes a promise, pauses this function — and only this function — until the promise settles, then hands back the unwrapped value. A rejected promise throws instead, which means ordinary try/catch works again.

async function makeDinner() {
  try {
    console.log(await step("Boil pasta", 300));
    console.log(await step("Make sauce", 200));
    console.log(await step("Serve", 100));
    return "Dinner is ready";
  } catch (err) {
    return "Caught: " + err.message;
  }
}

const promise = makeDinner();
console.log("Chop the salad while waiting");
console.log(await promise);
Chop the salad while waiting
Boil pasta done
Make sauce done
Serve done
Dinner is ready

"Chop the salad" still prints first: makeDinner froze at its first await, but the program kept going. An async function always returns a promise — whatever it returns arrives wrapped, which is why the caller awaits it.

Promise.all, allSettled, any, race and Promise.try

Awaiting independent tasks one at a time is the most common async/await mistake. Three 300 ms steps in a row cost the sum; Promise.all starts them together and costs the slowest:

let t = Date.now();
await step("pasta", 300);
await step("sauce", 300);
await step("salad", 300);
console.log("One at a time:", Date.now() - t, "ms");

t = Date.now();
const dishes = await Promise.all(
  [step("pasta", 300), step("sauce", 300), step("salad", 300)]);
console.log("Promise.all:  ", Date.now() - t, "ms", dishes);
One at a time: 915 ms
Promise.all:   312 ms [ 'pasta', 'sauce', 'salad' ]

Promise.all is all-or-nothing: one rejection rejects the whole batch. Its cousins cover the other cases. Promise.allSettled never rejects and reports every result ([ 'fulfilled', 'rejected' ] in the video's run). Promise.any returns the first success and ignores failures — perfect for mirrors of the same download. Promise.race returns the first to settle, success or failure, which is how timeouts are built. And ES2025's Promise.try starts a chain from any function, so even a synchronous throw lands in your catch as a rejection.

fetch and Array.fromAsync

The real world of promises is the network. fetch(url) returns a promise that fulfils with a response object as soon as the headers arrive; the body is still streaming, so res.json() is a second promise. Two awaits per request — and independent requests are perfect for Promise.all:

const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const todo = await res.json();
console.log(res.status, todo.title);

const [r1, r2] = await Promise.all([
  fetch("https://jsonplaceholder.typicode.com/users/1"),
  fetch("https://jsonplaceholder.typicode.com/users/2"),
]);
console.log((await r1.json()).name, "and", (await r2.json()).name);
200 delectus aut autem
Leanne Graham and Ervin Howell

ES2026 adds Array.fromAsync: like Array.from, but for async sources (an async generator, or promises arriving one by one). It awaits each item and gives you one promise of the whole array — await Array.fromAsync(backup()) in the video collects three pretend downloads into [ 'photos.zip', 'music.zip', 'docs.zip' ].

One last prediction

async function cook() {
  console.log("one");
  const msg = await Promise.resolve("two");
  console.log(msg);
  return "three";
}

cook().then((msg) => console.log(msg));
console.log("four");
one
four
two
three

An async function runs like a normal function until its first await. Then it suspends and hands control back — even when the promise is already resolved — so the caller's "four" beats the resumed function's "two", and the return value "three" arrives last through the then.

What you learned

  • The event loop: one thread, slow work beside the stack, callbacks queue up when it finishes.
  • A promise settles once: pending, then fulfilled or rejected; then chains, catch handles, finally always runs.
  • await pauses the function, never the program, and makes try/catch work for async code.
  • Promise.all for a batch, allSettled for every result, any for the first success, race for the first to settle, Promise.try for a safe start.
  • fetch is two awaits (response, then body); ES2026's Array.fromAsync collects an async source into an array.

Common questions

Is await the same as blocking? No. await suspends only the async function it appears in; the rest of the program keeps running. The quiz above proves it: the caller's console.log("four") runs while cook is suspended at its await.

When should I use .then instead of await? Inside an async function, prefer await — it reads top to bottom and works with try/catch. .then is still right at the top level of older scripts, or when you want to attach a handler and move on without waiting. Avoid mixing both styles on the same promise.

Does Promise.all run things in parallel? It runs them concurrently: all the timers or requests are started before any is awaited, so they overlap. JavaScript itself still executes your code on one thread; the waiting overlaps, not the computation.

What happens if one promise in Promise.all rejects? The combined promise rejects immediately with that error, and the other results are discarded (the underlying tasks still run to completion). If you need every outcome, use Promise.allSettled, which never rejects and reports { status, value } or { status, reason } per item.

Why does my async function return a pending promise when I console.log it? Because every async function returns a promise, and you logged it before it settled. Await it (console.log(await fn())) or attach a then to see the value.

Next lesson: stacks and queues — building a proper queue (and why shift() is a trap), and checking brackets with a stack.

This article goes with the video JavaScript Promises and async/await: then, catch, Promise.all. Watch it on YouTube.