Understand the idea

fetch requests a resource and returns a promise. For a static site, a local JSON file can supply gallery records or a searchable index.

await pauses an async function until a promise settles. fetch does not reject merely because a server returns 404; check response.ok. Parsing JSON can also fail, so keep both the request and parsing in the error-handling block. response.ok covers HTTP statuses from 200 through 299. Awaiting the request does not freeze the browser. This example logs failures; a real interface should also tell the reader that loading failed.

Read the example

This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.

JavaScript · EXAMPLE
async function loadPlaces() {
  try {
    const response = await fetch("/data/places.json");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const places = await response.json();
    console.log(places);
  } catch (error) {
    console.error("Could not load places:", error);
  }
}
loadPlaces();

A small mistake, explained

What goes wrong

Assuming a fulfilled fetch promise means success can lead you to parse an HTML error page as JSON.

How to fix it. Check the HTTP status and inspect the response body in the Network panel. Also verify that the data has the shape your code expects.

Try it yourself

Create /data/places.json containing ["Erfurt", "Berlin"] and serve the site locally. Test both the correct and an incorrect filename.

Further reading

Fetch Standard

Original explanation and example prepared for HTML code FYI with AI assistance. Test the code in your own context. How these guides are made.