Async and fetch

Request data over the network without freezing the interface.

Beginner 16 min read Lesson 11 of 480 Challenge included
What you will be able to do
  • Use async and await
  • Check response.ok
  • Handle loading and error states

Network requests take time. Promises let the browser keep painting while you wait. async/await makes that flow read like synchronous code.

fetch.jsJavaScript
async function loadCourses() {
  try {
    const response = await fetch("/api/courses");
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    const courses = await response.json();
    return courses;
  } catch (error) {
    console.error("Could not load courses", error);
    return [];
  }
}
  1. 01
    Start loading

    Show a skeleton or spinner immediately so the interface never feels frozen.

  2. 02
    Await the response

    fetch only rejects on network failure — check response.ok for 4xx and 5xx.

  3. 03
    Parse once

    Call response.json() exactly once. The body stream can only be consumed once.

  4. 04
    Handle both paths

    Render the data or a clear, actionable error. Never leave a permanent spinner.

Your turn

Load and render

Medium

Write an async function that fetches /api/lessons, checks the response and returns the parsed JSON.

JAVASCRIPT · starter
async function getLessons() {
  // your code here
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Does fetch reject when the server returns 404?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Storage and state
Lesson 11 of 480 · 0% of course