Promises, async/await & fetch
Load data from an API with fetch and handle loading and error states.
By Invicly Tech, , in Frontend with React & Next.js. About 8 minutes to read.
In short
Network requests take time, so JavaScript handles them asynchronously with promises. async/await makes that code read top to bottom, and fetch is the built-in way to call APIs.
Explained simply
Some work takes time: downloading data, waiting for a timer, reading a file. JavaScript in the browser runs on one main thread, so if it simply waited, the whole page would freeze. Instead, it starts the slow job, keeps going, and handles the result later.
A promise is the object that represents that later result. Think of the buzzer a restaurant gives you while your food is cooked. You can sit down and chat. When it buzzes, the food is ready, or the kitchen tells you something went wrong.
async and await are a nicer way to write promise code. Inside an async function, await pauses that function until the promise settles, without blocking the rest of the page. Your code reads top to bottom like normal steps.
fetch is the built-in way to make HTTP requests. A good fetch always handles three states the user can see: loading (show a spinner), success (show the data) and error (show a message and a way to retry).
Press Play on a diagram to walk through it one step at a time.
- UI to Your code: User opens page1User opens page
- Your code to UI: Show loading state2Show loading state
- Your code to API server: fetch('/api/posts')3fetch('/api/posts')
- API server to Your code: Response with JSON body4Response with JSON body
- 5Check res.ok, parse JSONYour code to Your code: Check res.ok, parse JSON
- Your code to UI: Render data or error6Render data or error
- 1Run call stack
Execute the current synchronous code to completion
- 2Drain microtasks
Run resolved promise callbacks
- 3Render if needed
Browser may update the screen
- 4Next task
Take the next timer, event or network callback
- Back to step 1
- 1Created
fetch(url) returns a pending promise
- 2Pending
Your code keeps running meanwhile
- 3Settled
Fulfilled with a value or rejected with an error
- 4Callback queued
then/catch or code after await joins the microtask queue
- 5Runs
When the call stack is empty
- const a = await getUser()
- const b = await getPosts()
- Time = a + b
- Use when b needs a's result
- const [a, b] = await Promise.all([...])
- Both start at once
- Time = the slower of a and b
- Use for independent requests
In depth
Microtasks vs macrotasks
The event loop has two waiting lines. Promise callbacks (then, catch and code after await) go in the microtask queue. Timers, user events and network callbacks go in the task queue, sometimes called the macrotask queue.
When the call stack becomes empty, the browser runs every microtask first, then one task, then all microtasks again, and gives the page a chance to repaint between tasks. So Promise.resolve().then(...) always runs before setTimeout(..., 0), even though both seem to mean "as soon as possible".
This also means a long synchronous loop blocks everything, including clicks and painting. Split heavy work into chunks or move it to a Web Worker.
- Sync code runs first, to completion
- Then all microtasks (promises)
- Then one macrotask (timer, event)
- Repaint can happen between tasks
- Step 1Sync code
console.log("A") runs first
- Step 2Stack empty
Event loop checks the queues
- Step 3Microtask
Promise.then logs "B"
- Step 4Task
setTimeout(..., 0) logs "C"
Error handling that actually works
A rejected promise that nobody catches shows an "Uncaught (in promise)" error. With async/await, wrap awaits in try/catch, and use finally for cleanup like hiding a spinner.
fetch itself only rejects on network failure, such as being offline or a blocked request. A 404 or 500 response still resolves. Always check response.ok (true for status 200 to 299) and throw your own error otherwise. Also remember that response.json() can throw if the body is not valid JSON.
Running things in parallel
Awaiting two requests one after the other takes the sum of their times. If they do not depend on each other, start both first and await them together with Promise.all. It resolves when all finish and rejects as soon as one fails.
Promise.allSettled waits for all and tells you which succeeded, which is good for dashboards where one failing widget should not break the rest. Promise.race settles with the first one to finish, which is useful for timeouts.
- Promise.all: all or nothing
- Promise.allSettled: every result, success or failure
- Promise.race: first to settle wins
- Promise.any: first success wins
Cancelling requests
If a user types in a search box quickly, older requests may come back after newer ones and show stale results. An AbortController lets you cancel a fetch. Create one, pass controller.signal to fetch, and call controller.abort() when the request is no longer needed. The fetch then rejects with an AbortError, which you can ignore. AbortSignal.timeout(5000) gives you a signal that aborts after 5 seconds.
- User to Search code: Types "re"1Types "re"
- Search code to API: fetch ?q=re with signal2fetch ?q=re with signal
- User to Search code: Types "react"3Types "react"
- Search code to API: abort() old request, fetch ?q=react4abort() old request, fetch ?q=react
- API to Search code: Results for react5Results for react
- Search code to User: Shows fresh results; AbortError ignored6Shows fresh results; AbortError ignored
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Understand the event loop~1h
- 2Chain promises with then/catch~1h
- 3Rewrite promise code with async/await~1h
- 4Fetch JSON from an API~1h
- 5Show loading and error states~1h
Key points
- A promise represents a value that will be ready later, or an error.
- await pauses only the async function, not the whole page.
- fetch only rejects on network failure; check res.ok for HTTP errors like 404.
- Always show loading and error states so users know what is happening.
Key terms
Tap a card to flip it. 0/4 known
Examples
async function loadPosts() {
status.textContent = 'Loading...';
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();
status.textContent = `${posts.length} posts loaded`;
} catch (err) {
status.textContent = `Failed: ${err.message}`;
}
}
const status = document.querySelector('#status');
loadPosts();Loading, success and error states with async/await.
Predicting the output order
Step 1: synchronous logs run first, so A then D. Step 2: when the stack is empty, microtasks run, so the promise callback logs C. Step 3: only then does the timer task run and log B. Final order: A, D, C, B. This is the event loop in action.
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// Output: A, D, C, BA search box that ignores stale results
Each keystroke starts a search. Step 1: keep the controller from the previous request. Step 2: before a new search, abort the old one. Step 3: fetch with the new signal and check response.ok. Step 4: ignore AbortError, because it is expected, and show any other error. Old answers can no longer overwrite new ones.
let controller;
async function search(q) {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch("/api/search?q=" + encodeURIComponent(q), { signal: controller.signal });
if (!res.ok) throw new Error("HTTP " + res.status);
render(await res.json());
} catch (err) {
if (err.name !== "AbortError") showError(err.message);
}
}Quick reference
- Order: sync code, then all microtasks (promises), then the next task (timers, events)
- fetch resolves on 404/500; check res.ok yourself
- Independent requests: await Promise.all([a(), b()])
- Use try/catch/finally around await; hide spinners in finally
- Cancel with AbortController; time out with AbortSignal.timeout(ms)
- await only pauses the current async function, not the page
- Always encodeURIComponent user input in query strings
Common mistakes
- Assuming fetch throws on a 404 or 500 response.
- Forgetting await, so you get a pending promise instead of data.
- Awaiting independent requests one by one instead of using Promise.all.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a function wait(ms) that returns a promise resolving after ms milliseconds, then use it to log "done" after 1 second.
- Exercise 2medium
Write getJSON(url) that fetches a URL, throws an Error with the status for non-2xx responses, and returns the parsed JSON.
- Exercise 3hard
Write retry(fn, times) that calls the async function fn and, if it throws, tries again up to times attempts in total, waiting 500ms, then 1000ms, then 2000ms between tries.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is JavaScript multithreaded?
- Your page code runs on one main thread. The browser does network and timers in the background, and you can use Web Workers for heavy computation on other threads.
- Should I use then or async/await?
- Prefer async/await for readability. then is still useful for short one-liners, and both work with the same promises.
- Can I use await at the top level?
- Yes, inside ES modules, such as script type="module" or files bundled by Vite. In classic scripts you need an async function.