Free beginner tutorial

JavaScript Async and Await with Fetch

Learn JavaScript async and await, fetch JSON data, check HTTP responses and handle request errors.

Why asynchronous code is useful

A network request takes time. JavaScript can continue running other work while it waits for a response. An async function lets you use await to write that sequence clearly.

Request and read JSON

fetch() returns a promise. Check response.ok because an HTTP error status does not by itself make the promise reject.

async function loadItems() {
  try {
    const response = await fetch("data/items.json");

    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    const items = await response.json();
    console.table(items);
  } catch (error) {
    console.error("Could not load items:", error);
  }
}

loadItems();

The request above reads the sample items.json file stored beside this lesson. Its JSON response is an array of objects, so console.table() displays the returned rows in the browser developer console.

Handle failures

The try...catch block handles network errors and errors thrown when the response status is not successful. The example uses a same-origin file. If you replace it with another domain, that server may need to allow cross-origin requests.

Open this lesson through a local web server or the live website. Browsers block many fetch requests from pages opened directly with a file:// URL. Do not place secret API keys in front-end JavaScript.