Skip to content
Visual explainer 5h to learn 5 steps

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.

Topic 8 of 36

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.

SequenceLoading data with fetch
UI
Your code
API server
  1. 1User opens page
    UI to Your code: User opens page
  2. 2Show loading state
    Your code to UI: Show loading state
  3. 3fetch('/api/posts')
    Your code to API server: fetch('/api/posts')
  4. 4Response with JSON body
    API server to Your code: Response with JSON body
  5. 5Check res.ok, parse JSON
    Your code to Your code: Check res.ok, parse JSON
  6. 6Render data or error
    Your code to UI: Render data or error
CycleThe event loop
  1. 1
    Run call stack

    Execute the current synchronous code to completion

  2. 2
    Drain microtasks

    Run resolved promise callbacks

  3. 3
    Render if needed

    Browser may update the screen

  4. 4
    Next task

    Take the next timer, event or network callback

  5. Back to step 1
FlowThe life of a promise
  1. 1
    Created

    fetch(url) returns a pending promise

  2. 2
    Pending

    Your code keeps running meanwhile

  3. 3
    Settled

    Fulfilled with a value or rejected with an error

  4. 4
    Callback queued

    then/catch or code after await joins the microtask queue

  5. 5
    Runs

    When the call stack is empty

CompareSequential vs parallel awaits
Sequential
  • const a = await getUser()
  • const b = await getPosts()
  • Time = a + b
  • Use when b needs a's result
Parallel
  • 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
FlowOutput order of one script
  1. Step 1
    Sync code

    console.log("A") runs first

  2. Step 2
    Stack empty

    Event loop checks the queues

  3. Step 3
    Microtask

    Promise.then logs "B"

  4. Step 4
    Task

    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.

SequenceCancelling a stale search
User
Search code
API
  1. 1Types "re"
    User to Search code: Types "re"
  2. 2fetch ?q=re with signal
    Search code to API: fetch ?q=re with signal
  3. 3Types "react"
    User to Search code: Types "react"
  4. 4abort() old request, fetch ?q=react
    Search code to API: abort() old request, fetch ?q=react
  5. 5Results for react
    API to Search code: Results for react
  6. 6Shows fresh results; AbortError ignored
    Search code to User: Shows fresh results; AbortError ignored

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Understand the event loop~1h
  2. 2
    Chain promises with then/catch~1h
  3. 3
    Rewrite promise code with async/await~1h
  4. 4
    Fetch JSON from an API~1h
  5. 5
    Show 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

js
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.

js
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// Output: A, D, C, B

A 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.

js
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.

Question 1

1Which runs first after the current script finishes: a resolved promise's then, or setTimeout(fn, 0)?

Question 2

2Two independent requests take 300ms and 500ms. How long does await Promise.all take?

Question 3

3When does fetch reject?

Question 4

4A dashboard loads 4 widgets and one API fails. Which helper lets the other 3 still show?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a function wait(ms) that returns a promise resolving after ms milliseconds, then use it to log "done" after 1 second.

  2. Exercise 2medium

    Write getJSON(url) that fetches a URL, throws an Error with the status for non-2xx responses, and returns the parsed JSON.

  3. 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.

Go deeper

ShareXLinkedInWhatsApp