async/await and fetch
async/await is syntax on top of Promises that lets async code read top to bottom like normal code, with plain try/catch for errors. Combined with fetch it is how you call real APIs, as long as you remember that fetch does not reject on a 404.
14.1 The problem with a then chain
- Every step lives in its own then callback, so a value from one step (user) is not directly available in the next.
- More steps make a longer chain that no longer reads like normal code.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)); function showOrders() { wait(300, "Asha") .then((user) => { console.log("User:", user); return wait(300, 2); }) .then((orders) => { console.log("Orders:", orders); }) .catch((err) => console.log(err.message));}showOrders();User: AshaOrders: 214.2 Fix: async/await with try/catch
- async before a function allows await inside it.
- await pauses the function until the Promise settles; the resolved value goes straight into a variable.
- user and orders are both in scope on the same line.
- A rejected Promise throws at the await, so a normal try/catch handles it.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v)); async function showOrders() { try { const user = await wait(300, "Asha"); const orders = await wait(300, 2); console.log(`${user}: ${orders} orders`); } catch (err) { console.log("Error:", err.message); }} showOrders();Asha: 2 orders14.3 How await works
- Step 1
1.Async function is called and starts running normally
- Step 2
2.Reaches await -> the function pauses (the caller keeps running)
- Step 3
3.Promise settles
- Step 4
4.Resolved -> value comes back, function continues
- Step 5
5.Rejected -> error thrown at await -> catch block
- Step 6
6.The async function itself always returns a Promise
const wait = (ms) => new Promise((r) => setTimeout(r, ms)); async function load() { console.log("1. Start"); await wait(300); console.log("3. Done");} load();console.log("2. Outside");1. Start2. Outside3. Done- await pauses only its own async function, not the whole program.
- How the rest keeps running is explained by the event loop (next topic).
14.4 A real API call with fetch
- fetch is built into browsers and Node; await fetch(url) gives a Response object.
- res.json() parses the body into a JS object and also returns a Promise, so await it too.
const API = "https://dummyjson.com/users"; async function getUser(id) { const res = await fetch(`${API}/${id}`); const user = await res.json(); return user;} async function main() { const user = await getUser(1); console.log(user.firstName);}main();Emily- Step 1
1.await fetch(url, { signal })
- Step 2
2.Network failed or aborted? -> fetch rejects -> catch
- Step 3
3.Got a Response -> check res.ok (status 200-299)
- Step 4
4.Not ok (404, 500) -> throw new Error(`HTTP ${res.status}`)
- Step 5
5.ok -> await res.json() -> use data
fetch rejects only on network errors, never on HTTP error statuses
14.5 Checkpoint: does a 404 go to catch?
const API = "https://dummyjson.com/users"; async function main() { try { const res = await fetch(`${API}/999`); console.log("Status:", res.status); } catch (err) { console.log("Catch:", err.message); }}main();Status: 404- No: for fetch, 404 or 500 is still a successful response.
- So always check res.ok and throw yourself.
async function getUser(id) { const res = await fetch(`${API}/${id}`); if (!res.ok) { throw new Error(`HTTP ${res.status}`); } return res.json();} getUser(999) .then((u) => console.log(u.firstName)) .catch((err) => console.log(err.message));// Without the res.ok check: undefined// With it: HTTP 404 (in catch)14.6 Sequential vs parallel
// Sequential: ~600msasync function loadPage() { const user = await wait(300, "Asha"); const cart = await wait(300, 2); console.log(user, cart);} // Parallel: ~300msasync function loadPage() { const [user, cart] = await Promise.all([ wait(300, "Asha"), wait(300, 2), ]); console.log(user, cart);}| Point | await one by one | await Promise.all([...]) |
|---|---|---|
| When the 2nd starts | After the 1st finishes | Both start together |
| Total time (300ms + 300ms) | ~600ms | ~300ms |
| Use when | Step 2 needs step 1's result | Calls are independent |
| On one failure | Stops at that await | Rejects immediately |
14.7 Cancel a request: AbortController
- Use it when a request has become useless, e.g. the user typed a new search word.
- Pass controller.signal to fetch; controller.abort() makes fetch reject with an AbortError.
- For a simple timeout, AbortSignal.timeout(ms) works too.
const API = "https://dummyjson.com/users";const controller = new AbortController(); async function search() { try { const res = await fetch(`${API}/1`, { signal: controller.signal, }); console.log("Status:", res.status); } catch (err) { console.log("Error:", err.name); }}search();controller.abort();Error: AbortError14.8 Common mistakes
- Not checking res.ok: a 404 error body is treated as data (firstName is undefined).
- Awaiting independent calls one after another (slow); use Promise.all.
- No try/catch around awaits: a rejection becomes an unhandled error.
- Believing await blocks the whole program: it pauses only its own function.
- Forgetting that res.json() also returns a Promise.
14.9 Interview tips
- async/await is readable syntax on top of Promises.
- An async function always returns a Promise; await pauses that function until the Promise settles.
- fetch does not reject on 404/500; check res.ok and throw.
- Run independent awaits in parallel with Promise.all.
- Cancel stale requests with AbortController (AbortError).