Web Development · Beginner level

Beginner level · Module 4: Modern JavaScript and Fetching Data · Lesson 2 of 3

Fetch and async/await

Request JSON data with fetch, wait for it with async/await and check for HTTP errors.

In this lesson you will

  • Fetch JSON with async/await
  • Check response.ok and catch network errors

Key concepts

fetchasync/awaitresponse.oktry/catch

The lesson

fetch(url) requests a resource and returns a promise. Inside an async function, const response = await fetch("events.json"); waits for the response, and const data = await response.json(); reads the JSON body.

fetch only fails for network problems. A missing file still returns a response, with status 404, so check if (!response.ok) and throw an error yourself.

Wrap the request in try/catch so a failure produces a helpful message instead of a broken page. The DevTools Network tab shows each request and its response.

Step by step

  1. Create events.json with five events.
  2. Fetch it in an async function and log the data.
  3. Check response.ok and throw for errors.
  4. Catch errors and log a clear message.

Practice activity

Load the events from JSON and render them as cards.

Expected result: The cards display the events from the file, and a wrong file name produces a clear error message.

Check your understanding

  1. Does fetch throw an error for a 404 response?

    Show answer

    No; you must check response.ok yourself.

  2. What does await response.json() return?

    Show answer

    The parsed JSON data.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.