Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Promises and async/await Without Surprises

Turn a sequential loader into parallel code with Promise.all, survive partial failures with Promise.allSettled, and dodge the classic await mistakes.

Contentsand lesson path

What you will learn

  • Write promise-based code with async/await, running independent requests in parallel with Promise.all or Promise.allSettled and handling every rejection.

Prerequisites: JavaScript Foundations

01. The problem

A product page needs two pieces of data: the signed-in customer's profile and their recent orders. Each lookup takes about 300 ms. The page should show everything as soon as possible, survive one service being down, and never show data from the wrong lookup. That is the whole brief — the rest of this lesson is writing it with promises and not being surprised by the result.

The examples run in Node.js (tested with 22.23) with a wait(ms, value) helper that resolves after a delay, standing in for real network calls. Every timing principle transfers directly to fetch, which the next lesson introduces. The promise mechanics themselves — states, then, rejection — are the ones from the JavaScript foundations skill; here we put them to work under time pressure.

02. Step 1: the sequential version, and what await actually does

JavaScript · sequential.mjs
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function loadPage() {
  const start = Date.now();
  const profile = await wait(300, 'profile');
  const orders = await wait(300, 'orders');
  const ms = Math.round((Date.now() - start) / 100) * 100;
  console.log(`${profile} + ${orders} took ~${ms} ms`);
}

loadPage();
Expected output (timings are approximate)
profile + orders took ~600 ms

About 600 ms for two 300 ms lookups: the second one starts only after the first has finished. await pauses the function until that one promise settles — it does not start anything, and it does not run things concurrently. Marking a function async changes what it returns (a promise) and licenses the await keyword inside; it does not make anything run in parallel.

These two requests are independent — neither needs the other's result — so waiting for them one after another is pure waste. The fix is to start both, then wait.

03. Step 2: start both, then wait — Promise.all

JavaScript · parallel.mjs
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function loadPage() {
  const start = Date.now();
  const [profile, orders] = await Promise.all([
    wait(300, 'profile'),
    wait(300, 'orders'),
  ]);
  const ms = Math.round((Date.now() - start) / 100) * 100;
  console.log(`${profile} + ${orders} took ~${ms} ms`);
}

loadPage();
Expected output (timings are approximate)
profile + orders took ~300 ms

The calls happen when the promises are created — the two wait(...) calls inside the array start immediately. Promise.all only waits: it resolves when every promise in the list has resolved, giving the values in the same order as the inputs. The order is by position, not by completion: even if the orders request had resolved first, destructuring would still bind profile to the profile value. Total time falls to about 300 ms, the length of the slowest request.

The catch is the failure mode. Promise.all rejects as soon as one promise rejects, with that first rejection — even if the other promises would have delivered useful values. The remaining requests are not cancelled; they keep running and their results are simply dropped. For two pieces that the page needs together, all-or-nothing is the right contract: if the profile is missing, orders alone are not worth rendering.

04. Step 3: partial failures — Promise.allSettled

JavaScript · allsettled.mjs
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

async function loadDashboard() {
  const results = await Promise.allSettled([
    wait(200, 'profile loaded'),
    fail(100, 'orders service is down'),
    wait(250, 'cart loaded'),
  ]);
  for (const result of results) {
    if (result.status === 'fulfilled') {
      console.log('ok:  ', result.value);
    } else {
      console.log('fail:', result.reason.message);
    }
  }
}

loadDashboard();
Expected output
ok:   profile loaded
fail: orders service is down
ok:   cart loaded

A dashboard is the opposite case: five widgets, and one failing widget must not stop the other four. Promise.allSettled waits for every promise and reports each outcome as either { status: "fulfilled", value } or { status: "rejected", reason }. It does not reject when one of its inputs rejects, so there is nothing for try/catch to catch — you branch on status instead, and each widget can render its data or its own error.

Choose the combinator from what a failure means:

  • Promise.all — you need everything, so the first rejection aborts the await. Good for "profile + orders" style pages.
  • Promise.allSettled — independent pieces, each shown or failed on its own. Good for dashboards and tiles.
  • Promise.race — settles with whichever promise settles first, success or failure. Useful for timeouts: race the work against a timer.
  • Promise.any — settles with the first success; rejects only if every promise fails. Good for trying mirrors.

05. Step 4: two mistakes worth seeing once

First mistake: calling an async function without awaiting it, on purpose, to "save time". The call returns a promise that nobody keeps — a floating promise. Watch what happens when one of them rejects with no await and no catch anywhere:

JavaScript · unhandled.mjs
async function save(n) {
  if (n === 2) throw new Error(`save ${n} failed`);
  return `saved ${n}`;
}

const results = [1, 2, 3].map((n) => save(n));
console.log('map returned:', results.constructor.name);
console.log('map returned promises; nobody is awaiting them');
await new Promise((resolve) => setTimeout(resolve, 50));
console.log('this line never runs');
Illustrative output (Node.js 22.23; paths trimmed, frames and version differ)
map returned: Array
map returned promises; nobody is awaiting them
file:///…/unhandled.mjs:2
  if (n === 2) throw new Error(`save ${n} failed`);
                     ^

Error: save 2 failed
    at save (file:///…/unhandled.mjs:2:22)
    at file:///…/unhandled.mjs:6:38
    at Array.map (<anonymous>)
    … (further frames trimmed)

Node.js v22.23.2

The rejection had no handler, so Node terminated the process — the final console.log never ran. In a browser an unhandled rejection does not kill the page: the console shows Uncaught (in promise) and the window fires an unhandledrejection event that error-reporting code can listen for. But none of your code handled the failure, so the user sees nothing. map returning an array of promises is not a bug by itself; forgetting to await that array is. The corrections: await Promise.all(ids.map(save)) when parallel is fine, or a for…of loop with await inside when each step must finish before the next starts.

Second mistake: expecting a promise to deliver twice. A promise settles at most once. Both of these resolve calls run, but only the first counts:

JavaScript · settle-once.mjs
const p = new Promise((resolve) => {
  resolve('first');
  resolve('second');
  console.log('executor ran to the end');
});

p.then((value) => console.log('got:', value));
Expected output
executor ran to the end
got: first

Later calls to resolve or reject are silently ignored, which is why wrapping a callback that can fire many times (an event listener, a stream chunk) in a promise needs care: resolve on the first event, and decide deliberately what the rest should do.

06. Mistakes to watch for

07. Check your understanding

Practice check · 3 questions

Combining promises in practice

Pick the contract that matches each situation.

Q1. Five requests run in parallel with `await Promise.all(...)`. One rejects after 100 ms; the other four succeed at 300 ms. What does the await do?
Q2. A promise executor calls `resolve("first")` and, a few lines later, `resolve("second")`. What does the promise settle with?
Q3. `loadStats()` is an async function that rejects for some inputs. A colleague calls it without `await` as a "fire and forget". What is the concrete risk?
Practice only: not graded, not saved, not evidence.

08. Apply it

These patterns feed straight into this skill's practice project, which loads search results with fetch:

  1. Write a delay(ms) helper as a promise wrapper around setTimeout, and use it to rebuild the sequential/parallel comparison with your own numbers.
  2. Find one await in code you have written that sits between two independent requests, and turn it into a destructured await Promise.all.
  3. Build a three-widget loader with Promise.allSettled where each widget logs its own outcome, then decide which widgets would justify Promise.all instead — and why.

09. Review prompt

Without looking back: what does await do to the calling function, and what does async change about a function's return value? How long do two 300 ms requests take with sequential awaits versus Promise.all, and what happens to the survivors when one promise inside Promise.all rejects? Which combinator reports every outcome, which one gives the first success, and why does Node exit when a floating promise rejects?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check