Async JavaScript: Promises, fetch(), and Not Freezing the Browser
Why JavaScript has only one thread, how Promises and async/await let you wait for network data without freezing the page, and the fetch() gotchas that bite everyone.
You'll learn why JavaScript refuses to block on slow network calls, how Promises and async/await actually work under the hood, and how to handle 404s, parallel requests, and timeouts safely with fetch(). Assumes basic familiarity with JavaScript functions and objects.
1. The one-barista coffee shop
JavaScript in the browser is single-threaded. That means it has one worker—one call stack—doing one thing at a time.
Imagine a coffee shop with a single barista. If a customer orders an espresso and the barista stands frozen at the machine staring at the beans for 45 seconds without taking anyone else's order, the line backs up out the door. Nobody can even ask for a napkin.
In a browser, "the line backing up" means the entire webpage freezes. Buttons stop clicking, text stops highlighting, animations stutter, and the browser eventually pops up "This page is not responding."
Network requests—fetching a user profile, loading posts, saving a form—take anywhere from 50 milliseconds to several seconds. That is an eternity to a CPU. So JavaScript does asynchronous I/O instead: the barista hands you a plastic buzzer, moves on to serve the next customer, and comes back to your order the moment the buzzer goes off.
In JavaScript, that plastic buzzer is called a Promise.
2. What a Promise actually is
A Promise is an object representing a value that does not exist yet, but will exist in the future (or fail trying).
Every Promise is in one of three states:
- Pending — still waiting (the buzzer is quiet).
- Fulfilled — succeeded and now holds a result value.
- Rejected — failed and holds an error.
Once a Promise is fulfilled or rejected, it is settled and can never change state again.
You can see a raw Promise by logging fetch(...) without waiting for it:
const result = fetch("https://api.github.com/users/octocat");
console.log(result);Promise { <pending> }fetch() did not return the GitHub user. It returned a pending Promise immediately—in microseconds—so JavaScript could keep the page responsive while the network request travels across the ocean.
3. Reading Promises with async and await
Years ago, you had to chain .then().then().catch() callbacks, which quickly turned into a sideways pyramid of doom. Modern JavaScript gives you async and await, which let you write asynchronous code that looks like normal top-to-bottom code without actually blocking the browser.
Mark a function with async, and you can pause inside that function with await until a Promise settles:
async function loadOctocat() {
const response = await fetch("https://api.github.com/users/octocat");
const user = await response.json();
console.log(user.login, "has", user.public_repos, "public repos");
}
loadOctocat();
console.log("I run BEFORE loadOctocat finishes!");I run BEFORE loadOctocat finishes!
octocat has 8 public reposLook closely at the order of those two lines:
loadOctocat()starts thefetch(), hitsawait, and hands control back to the browser so the rest of the script (and user clicks, scrolling, animations) keeps running.- That is why
"I run BEFORE loadOctocat finishes!"prints first. - When the HTTP headers arrive, JavaScript resumes
loadOctocat()right where it paused.
Notice there are two awaits:
await fetch(url)waits for the server to start replying (HTTP status + headers).await response.json()waits for the response body to finish downloading and parses it from text into a JavaScript object.
Also: every async function always returns a Promise, even if you return "hello" inside it.
Open your browser DevTools Console, paste loadOctocat(), and watch the two lines print out of top-to-bottom order.
4. The fetch() trap: 404 is not an error to fetch()
Here is the trap that catches almost every developer their first week using fetch():
async function getBroken() {
try {
const res = await fetch("https://api.github.com/users/this-user-does-not-exist-99999");
const data = await res.json();
console.log("Got data:", data);
} catch (err) {
console.log("Caught error:", err.message);
}
}
getBroken();You might expect catch to run because GitHub returned 404 Not Found. It does not.
fetch() only rejects its Promise if the network itself fails (no Wi-Fi, DNS failure, server unreachable). If the server successfully answers with 404 Not Found or 500 Internal Server Error, fetch() considers that a successful network trip and resolves normally!
If the server sends an HTML error page instead of JSON, res.json() crashes with SyntaxError: Unexpected token '<', leaving you wondering why a 404 turned into a JSON parsing error.
The fix: always check res.ok (which is true for status codes 200–299) right after fetch():
async function fetchJson(url) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Request failed with HTTP ${res.status}`);
}
return res.json();
}Now a 404 or 500 throws a clear error that your try / catch block actually catches.
Never call res.json() until you have checked if (!res.ok) throw new Error(...). Status 404 and 500 do not trigger catch on their own.
5. Sequential vs. parallel: stop waiting twice
Suppose you need to load two independent endpoints—say, a user's profile and their notifications. Beginners often write:
// Slow: waits for profile to finish BEFORE starting notifications
const profile = await fetchJson("/api/profile");
const notifications = await fetchJson("/api/notifications");If each request takes 400ms, the user waits 800ms for no reason—the second request did not even need anything from the first!
When requests are independent, fire both at the same time and wait for both buzzers together with Promise.all:
const [profile, notifications] = await Promise.all([
fetchJson("/api/profile"),
fetchJson("/api/notifications"),
]);Now both requests travel in parallel, and the total wait is ~400ms instead of 800ms.
One catch with Promise.all: it is all-or-nothing. If one request fails, Promise.all immediately rejects, even if the other succeeded. When you want all results regardless of whether one failed (like loading three independent dashboard widgets), use Promise.allSettled:
const results = await Promise.allSettled([
fetchJson("/api/weather"),
fetchJson("/api/stocks"),
]);
for (const r of results) {
if (r.status === "fulfilled") {
console.log("Loaded:", r.value);
} else {
console.warn("Widget failed:", r.reason.message);
}
}Compare Promise.all vs Promise.allSettled: if widget #2 returns a 500, Promise.all throws away widget #1's data, while Promise.allSettled lets you render widget #1 and show a fallback for #2.
6. Timeouts and cancellation with AbortController
By default, fetch() has no short timeout—if a server hangs silently, fetch() can sit pending for minutes. Even worse, if a user types in a search box or navigates away, old slow requests can arrive late and overwrite newer results (a classic race condition).
AbortController solves both problems cleanly:
async function fetchWithTimeout(url, ms = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} finally {
clearTimeout(timer);
}
}Notice the finally block: whether the request succeeds, throws a 404, or aborts, clearTimeout(timer) always cleans up the timer so you don't leak timers. Modern browsers also support AbortSignal.timeout(5000) directly when you only need a timeout without manual cleanup!
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Forgot await before fetch() or res.json() | Variable holds Promise { <pending> } instead of data | Add await inside an async function |
Skipped if (!res.ok) check | 404/500 pages crash later in res.json() | Check res.ok and throw a clear Error |
await inside a for loop for independent URLs | Requests run one-by-one instead of in parallel | Map to Promises and use Promise.all(...) |
array.forEach(async (item) => ...) | forEach ignores Promises and finishes before awaits | Use for (const item of array) or Promise.all(array.map(...)) |
No try / catch around await | Unhandled Promise rejection breaks the UI flow | Wrap await calls in try / catch and show a fallback state |
Practice
Predict the output before running each one. Answers follow.
Exercise 1. What order do A, B, C print in?
async function run() {
console.log("A");
await Promise.resolve();
console.log("B");
}
run();
console.log("C");Exercise 2. Why does this print "Done" before any user is fetched?
const names = ["octocat", "torvalds"];
names.forEach(async (n) => {
const res = await fetch(`https://api.github.com/users/${n}`);
console.log(n, res.status);
});
console.log("Done");Exercise 3. What happens if you await fetchJson(url) inside try { ... }, and fetchJson returns res.json() without await inside fetchJson?
Answers
Exercise 1 prints A, C, B. console.log("A") runs synchronously, then await pauses run() and schedules the rest as a microtask. console.log("C") finishes the current turn, and then B runs.
Exercise 2 prints "Done" first because Array.prototype.forEach does not wait for async callbacks—it fires both requests and moves straight to console.log("Done"). Use await Promise.all(names.map(...)) if you want to wait for all of them.
Exercise 3: If fetchJson does try { return res.json(); } catch ... without await, fetchJson's own catch won't catch a JSON parse error—the caller's try / catch will, because fetchJson returns the rejected Promise directly. If fetchJson itself needs to catch res.json() errors, write return await res.json().
What you learned
- JavaScript runs on one thread; a Promise is a placeholder for a future result so slow network calls don't freeze the UI.
async/awaitpauses only theasyncfunction while the browser stays responsive.fetch()does not reject on 404 or 500—always checkif (!res.ok).- Use
Promise.all(orPromise.allSettled) to run independent requests in parallel instead of awaiting one by one. - Use
AbortController(orAbortSignal.timeout) to cancel stale or hanging requests.