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.
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 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.
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
| Idea | Remember |
|---|---|
| Promise | a box: pending, then fulfilled or rejected, once |
.then / .catch | each .then gets what the step before returned; one .catch covers the chain |
await | pauses the function, not the program; an async function returns a promise |
Rejection with await | throws, so use try/catch |
fetch | rejects only when no answer comes; check res.ok; res.json() is a second promise |
Promise.all | start independent requests together, await them together |
| Order of events | plain 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.
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.
