Unays Learn · JavaScript

Fetching data with JavaScript: fetch, JSON and async/await

Many apps show data that lives somewhere else: weather, scores, search results. JavaScript loads it with fetch(), usually as JSON. This tutorial shows the whole pattern, including what to do when it fails.

What JSON looks like

JSON (JavaScript Object Notation) is text that describes data with objects, arrays, strings, numbers, booleans and null:

{
  "city": "Tirana",
  "temperature": 21.5,
  "sunny": true,
  "forecast": [22, 24, 19]
}

Convert between JSON text and JavaScript values with JSON.parse(text) and JSON.stringify(value). Keys and strings must use double quotes.

async and await

Loading data takes time, so fetch returns a promise: a value that will arrive later. Inside an async function, await pauses until it arrives without freezing the page:

async function loadPost() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const post = await response.json();
  console.log(post.title);
}

loadPost();

This example uses JSONPlaceholder, a free practice API that returns made-up posts.

Handling errors

Two things can go wrong: the network fails (fetch throws an error), or the server answers with an error status such as 404 (fetch does not throw for that). Handle both:

async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error("Request failed with status " + response.status);
  }
  return response.json();
}

try {
  const post = await getJson("https://jsonplaceholder.typicode.com/posts/1");
  console.log(post.title);
} catch (error) {
  console.log("Could not load the post:", error.message);
}

Top-level await, as in the try block above, works in JavaScript modules (<script type="module">). In a normal script, put it inside an async function.

Showing the data on a page

<button id="load">Load posts</button>
<p id="status" role="status"></p>
<ul id="posts"></ul>

<script type="module">
  const list = document.querySelector("#posts");
  const status = document.querySelector("#status");

  document.querySelector("#load").addEventListener("click", async () => {
    status.textContent = "Loading…";
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
      if (!response.ok) throw new Error("HTTP " + response.status);
      const posts = await response.json();
      list.replaceChildren(...posts.map(post => {
        const li = document.createElement("li");
        li.textContent = post.title;
        return li;
      }));
      status.textContent = "Loaded " + posts.length + " posts.";
    } catch (error) {
      status.textContent = "Sorry, the posts could not be loaded.";
    }
  });
</script>

Showing "Loading…" and a friendly error message tells people what is happening. role="status" makes screen readers announce the changes.

Try it yourself

Run the example in Unays Code. Then change the URL to a path that does not exist, such as /postz, to see your error handling work. Remember never to put secret API keys in browser JavaScript: anyone can read them.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].