Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

Async JavaScript: Promises, async/await, fetch and Promise.all

A promise is a box that fills later. Follow one through pending and fulfilled, see what await really pauses, why a 404 does not reject fetch, why res.json() is a second promise, and how Promise.all cut 591 ms to 309 ms.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Describe a promise as a box that is pending, then fulfilled or rejected, once
  • Chain .then and .catch, and explain what await pauses
  • Handle rejected promises with try/catch, check res.ok, and await res.json()
  • Run independent requests together with Promise.all

Before you start

  • JavaScript syntax: const, arrow functions, modules

Some things take time, like asking a server for data. JavaScript doesn't stop and wait for them. It hands you a promise instead and carries on. Once that one idea clicks, .then, await and fetch all fall into place.

A promise is a box that fills later

Say we call orderCoffee("Emma"). The coffee takes time, so instead of coffee we get a box. It comes back at once, but it's empty, and its state is pending. Later one of two things happens. If all goes well the box is fulfilled and holds a value, "Coffee for Emma"; .then is how you say "when there's a value, give it to me". If something goes wrong the box is rejected and holds an error, and .catch gets it. A promise settles only once and never changes after that.

A pending promise settles once: either fulfilled with a value, handled by .then, or rejected with an error, handled by .catch. pending empty box, returned at once resolve(value) reject(error) fulfilled "Coffee for Emma" rejected Error: No name on the order → .then(...) → .catch(...)
Pending first, then settled once: fulfilled with a value or rejected with an error.
// A promise is a box: pending now, settled later
function orderCoffee(name) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {         // takes 500 ms
      if (name) resolve("Coffee for " + name);
      else reject(new Error("No name on the order"));
    }, 500);
  });
}

const order = orderCoffee("Emma");
console.log(order);            // still empty
console.log("Doing other things");
setTimeout(() => console.log(order), 600);

const noName = orderCoffee("");
noName
  .then(msg => console.log(msg))     // skipped
  .catch(e => console.log("Rejected:", e.message));
Promise { <pending> }
Doing other things
Rejected: No name on the order
Promise { 'Coffee for Emma' }

order gets the box right away, and printing it shows Promise { <pending> }. "Doing other things" comes out immediately; nothing waited 500 ms. At 500 ms the timer calls resolve, and at 600 ms printing the same variable shows the value inside.

The second order has an empty name, which is falsy, so reject runs. The .then only runs when there's a value, so it's skipped, and the error lands in .catch. One .catch at the end of a chain catches a rejection from anywhere above it. (Forget the word new before Promise and Node stops with TypeError: Promise constructor cannot be invoked without 'new'.)

.then passes the value along

// Each .then gets what the step before it returned
const prices = { Keyboard: 50, Mouse: 25 };

function getPrice(item) {
  return new Promise(resolve => {
    setTimeout(() => resolve(prices[item]), 300);
  });
}

getPrice("Keyboard")
  .then(price => price * 2)          // two keyboards
  .then(total => total + 10)         // plus shipping
  .then(total => "Total: " + total)
  .then(text => console.log(text))
  .catch(err => console.log("Failed:", err.message));

console.log("Waiting for the price...");
Waiting for the price...
Total: 110

Every .then makes a new promise immediately, so the whole chain is built at once and "Waiting for the price..." prints first. After 300 ms the first box is fulfilled with 50. That goes into price * 2 = 100, then 100 + 10 = 110, then the text, then the log. Whatever each callback returns fills the next box. The usual mistake is .then(price => { price * 2 }): the braces need a return, so the next step gets undefined and prints Total: NaN.

What await really pauses

// await pauses this function, not the program
const prices = { Keyboard: 50, Mouse: 25 };
const getPrice = item => new Promise(resolve =>
  setTimeout(() => resolve(prices[item]), 300));

async function checkout(item) {
  console.log("1. checkout starts");
  const price = await getPrice(item); // pause here
  console.log("3. price is", price);
  return price * 2;           // fills its promise
}

const result = checkout("Keyboard");
console.log("2. the program goes on", result);
result.then(t => console.log("4. total is", t));
1. checkout starts
2. the program goes on Promise { <pending> }
3. price is 50
4. total is 100

Follow the numbers. checkout starts and prints 1. At await getPrice(item) it gets a pending box, and await lifts checkout off the call stack, paused on that line with its local values kept. checkout hands back a promise straight away, and the main script carries on and prints 2. Three hundred milliseconds later the price box is fulfilled with 50, a job to resume checkout goes into the queue, and it continues from the same line and prints 3.

await pauses the function, not the program. An async function always returns a promise, which is why line 2 shows Promise { <pending> }, and its return price * 2 fills that promise with 100 for the .then on the last line.

So what is await, really? It's .then written top to bottom: the rest of the function becomes the callback. Drop the await and price is the box itself; the run prints 3. price is Promise { <pending> } before line 2, and the total is NaN.

A rejected promise makes await throw

// A rejected promise makes await throw
const prices = { Keyboard: 50, Mouse: 25 };
const getPrice = item =>
  new Promise((resolve, reject) => setTimeout(() => {
    if (item in prices) resolve(prices[item]);
    else reject(new Error("No price for " + item));
  }, 300));

async function checkout(item) {
  try {
    const price = await getPrice(item);  // may throw
    console.log(item, "costs", price);
  } catch (err) {
    console.log("Caught:", err.message);
  } finally {
    console.log("Done with", item);
  }
}

checkout("Mouse").then(() => checkout("Laptop"));
Mouse costs 25
Done with Mouse
Caught: No price for Laptop
Done with Laptop

There's no price for a laptop, so that promise is rejected, and await throws the error right on that line like a normal throw. The log line is skipped and catch runs. finally runs either way. Remove the try/catch and nobody handles the rejection: Node prints Error: No price for Laptop and stops, and "Done with Laptop" never appears.

fetch: a request out, a Response back

fetch needs something to call, so the project has a tiny local server, server.js, built on Node's http module. It answers /tasks with three tasks after 300 ms, /users/1 after 200 ms, and anything else with a 404. Start it with node server.js in one terminal, and it prints Listening on http://localhost:3001. Run the fetch files in a second terminal.

// fetch: a request goes out, a Response comes back
const BASE = "http://localhost:3001";

async function loadTasks() {
  const res = await fetch(BASE + "/tasks");
  console.log(res.status, res.ok);
  console.log(res.headers.get("content-type"));

  const body = res.json();      // a SECOND promise
  console.log(body);
  const tasks = await body;
  console.log(tasks.length, "tasks:", tasks[0].title);
}
loadTasks();
200 true
application/json
Promise { <pending> }
3 tasks: Write report

fetch sends GET /tasks and returns a pending promise. When the status and headers arrive, it's fulfilled with a Response. res.ok is true for any status from 200 to 299. But the body isn't read yet. res.json() returns a second promise, which is why it prints as pending. Awaiting it reads the whole body and parses the JSON into real objects. It's two waits: one for the Response, one for the body. Forget the second await and tasks[0] is undefined, so you get TypeError: Cannot read properties of undefined (reading 'title').

200, 404, or no answer at all

// fetch rejects only when there is no answer at all
const urls = [
  "http://localhost:3001/users/1",    // 200
  "http://localhost:3001/users/99",   // 404
  "http://localhost:3999/users/1",    // no server
];

async function getJson(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

for (const url of urls) {
  try {
    const user = await getJson(url);  // .mjs
    console.log("User:", user.name);
  } catch (err) {
    console.log("Caught:", err.message);
  }
}
User: Emma
Caught: HTTP 404
Caught: fetch failed

A 404 is still an answer, so fetch's promise is fulfilled; only res.ok is false (it plays the same role as checking response.ok or calling raise_for_status() in Python's requests). That's why getJson checks it and throws its own error. The third address is a port where nothing listens. There's no answer at all, so this time the promise is rejected with TypeError: fetch failed. Delete the res.ok check and nothing complains about the 404; you just get User: undefined.

The file ends in .mjs, so it's a module and await works at the top level.

One after another, or both at once

// One after another, or both at the same time
const BASE = "http://localhost:3001";
let t0;
const ms = () => Date.now() - t0;

async function load(path) {
  const res = await fetch(BASE + path);
  const data = await res.json();
  console.log(" ", path, "done at", ms(), "ms");
  return data;
}

async function oneByOne() {
  t0 = Date.now();
  const tasks = await load("/tasks");      // 300 ms
  const user = await load("/users/1");     // + 200 ms
  console.log("one after another:", ms(), "ms");
}

async function together() {
  t0 = Date.now();
  const both = [load("/tasks"), load("/users/1")];
  const [list, user] = await Promise.all(both);
  console.log("Promise.all:", ms(), "ms");
  console.log(user.name, "has", list.length, "tasks");
}

oneByOne().then(together);

One captured run printed:

  /tasks done at 377 ms
  /users/1 done at 591 ms
one after another: 591 ms
  /users/1 done at 217 ms
  /tasks done at 308 ms
Promise.all: 309 ms
Emma has 3 tasks

Your milliseconds will differ a little; the shape won't.

Timeline. One after another: tasks runs 0 to 377 ms, then users runs 377 to 591 ms. Promise.all: both start at 0, users ends at 217 and tasks at 308, total 309 ms. 0300600 ms two awaits /tasks → 377 /users/1 → 591 Promise.all /tasks → 308 /users/1 → 217 591 ms: the waits add up 309 ms: about the slowest one
Two awaits in a row make the second request wait for the first, even though it doesn't need its result.

In oneByOne, /users/1 doesn't start until /tasks is done (377 ms, a bit over 300 because the first request also opens the connection), so the total is 591 ms. In together, both load calls start without await, giving an array of two pending promises, and Promise.all waits for both. The total is about the slowest one, 309 ms. The results come back in the order you passed them, not the order they finished, so destructuring into [list, user] is safe.

The trap: [await load("/tasks"), await load("/users/1")] looks parallel but is one after another again. A captured run of that version took 512 ms.

Quick recap

IdeaRemember
Promisea box: pending, then fulfilled or rejected, once
.then / .catcheach .then gets what the step before returned; one .catch covers the chain
awaitpauses the function, not the program; an async function returns a promise
Rejection with awaitthrows, so use try/catch
fetchrejects only when no answer comes; check res.ok; res.json() is a second promise
Promise.allstart independent requests together, await them together
Order of eventsplain code first, then promise callbacks, then timers

If you've used Python's asyncio, the shape is the same: an async def returns a coroutine, await pauses it, and asyncio.gather plays the part of Promise.all. In React this is the code that loads data from your API; TanStack Query wraps exactly these fetch calls.

Try it yourself

With the server running, add a third route, /projects, with a 400 ms delay, and load all three with Promise.all. Predict the total time before you run it, then check that it's close to 400 ms and not 900.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 11 of 59

Previous
JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
Next post
JavaScript in the Page: the DOM, querySelector and Events

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx

Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.

How a Web Page Works: HTML Tags, Elements and Attributes

A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.

Semantic HTML: header, nav, main, aside and footer as Page Landmarks

The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.

On this page

  • A promise is a box that fills later
  • .then passes the value along
  • What await really pauses
  • A rejected promise makes await throw
  • fetch: a request out, a Response back
  • 200, 404, or no answer at all
  • One after another, or both at once
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.