IntermediateLesson 19 of 306 min read

Fetch, promises and async/await: working with APIs

Load data from APIs with fetch, understand promises, and write clear async/await code with loading and error states.

In this lesson you will

  • Explain what an API and a promise are
  • Use fetch with then and with async/await
  • Show loading, success and error states
  • Know CORS and API key basics

About 20 minutes

Talking to the rest of the internet

When your weather app shows today’s forecast, it did not invent the numbers. When a news site loads “more stories”, the page did not reload. In both cases, JavaScript asked a server for data in the background, got a reply, and updated the page. The tool for this is fetch, and the servers you ask are called APIs (application programming interfaces). An API is a waiter for data: you send an order in a defined format, and it brings back a dish in a defined format, usually JSON.

The trouble with waiting

Fetching takes time: a fraction of a second, or ten. If JavaScript stopped everything to wait, the page would freeze. So the browser says: “I will start the request, you carry on, and I will tell you when the reply arrives.” The thing JavaScript holds while it waits is called a Promise, literally a promise of a future result. It is in one of three states: pending (waiting), fulfilled (success, with a value) or rejected (failed, with an error).

fetch with then

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(response => response.json())
  .then(user => {
    console.log(user.name);
  })
  .catch(error => {
    console.log("Something went wrong", error);
  });

Read it as a chain of steps. fetch returns a promise for the response. .then runs when it arrives. response.json() itself returns another promise (parsing takes time), so we chain another .then. .catch handles any failure along the way.

async and await: the readable way

async function loadUser() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");

    if (!response.ok) {
      throw new Error("Server said " + response.status);
    }

    const user = await response.json();
    console.log(user.name);
  } catch (error) {
    console.log("Failed:", error.message);
  }
}

loadUser();
  • async before a function lets you use await inside it and makes it return a promise.
  • await pauses that function until the promise settles, without freezing the page. The line after it runs with the real value.
  • try / catch handles errors the same way as in ordinary code.
  • response.ok is true for status codes 200 to 299. Fetch does not throw on a 404 or 500; you must check.
Good to know

The live editors on this page can’t reliably reach the internet, so the practice below uses a pretend server: a function that returns a promise after a short delay, exactly like fetch does. The skills transfer one to one, and the real-fetch examples above work on your own pages.

This fake fetchUser returns a promise after 1 second. Use async/await to get the user and print their name. Then call it with an id that doesn’t exist and handle the error.

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 1) resolve({ id: 1, name: 'Sara Khan' });
      else reject(new Error('User not found'));
    }, 1000);
  });
}

// write async function show(id) with try/catch

async function show(id) { try { const u = await fetchUser(id); console.log(u.name); } catch (e) { console.log(e.message); } }

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 1) resolve({ id: 1, name: 'Sara Khan' });
      else reject(new Error('User not found'));
    }, 1000);
  });
}

async function show(id) {
  try {
    const u = await fetchUser(id);
    console.log(u.name);
  } catch (e) {
    console.log('Error: ' + e.message);
  }
}
show(1);
show(99);

Showing fetched data on the page

async function showPosts() {
  const list = document.querySelector("#posts");
  list.textContent = "Loading...";

  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
    if (!res.ok) throw new Error("HTTP " + res.status);
    const posts = await res.json();

    list.innerHTML = "";
    for (const post of posts) {
      const li = document.createElement("li");
      li.textContent = post.title;
      list.append(li);
    }
  } catch (err) {
    list.textContent = "Could not load posts. Please try again.";
  }
}
showPosts();

Every request has three states a visitor can see: loading, success and error. A beginner’s page often handles only success. A professional’s handles all three, and the visitor never stares at a blank screen wondering what happened.

Simulate loading a list. Show ‘Loading…’ first, then after one second show the items, using the pretend server. Add a second button that makes it fail so you can see the error message.

<style>body{font-family:Arial;padding:14px} button{padding:8px 12px;margin-right:6px;background:#5A28C8;color:#fff;border:0;border-radius:8px} #o{margin-top:12px}</style>
<button id="ok">Load</button><button id="bad">Fail</button>
<div id="o"></div>
<script>
  function fakeFetch(shouldFail) {
    return new Promise((resolve, reject) => {
      setTimeout(() => shouldFail ? reject(new Error('Network down')) : resolve(['HTML', 'CSS', 'JavaScript']), 1000);
    });
  }
  const o = document.getElementById('o');
  async function load(fail) {
    // show Loading..., await fakeFetch(fail), then list items or error
  }
  document.getElementById('ok').onclick = () => load(false);
  document.getElementById('bad').onclick = () => load(true);
</script>

o.textContent = ‘Loading…’; try { const items = await fakeFetch(fail); o.innerHTML = items.map(i => ‘

  • ‘ + i + ‘
  • ‘).join(”); } catch (e) { o.textContent = ‘Error: ‘ + e.message; }

    <style>body{font-family:Arial;padding:14px} button{padding:8px 12px;margin-right:6px;background:#5A28C8;color:#fff;border:0;border-radius:8px} #o{margin-top:12px}</style>
    <button id="ok">Load</button><button id="bad">Fail</button>
    <div id="o"></div>
    <script>
      function fakeFetch(shouldFail) {
        return new Promise((resolve, reject) => {
          setTimeout(() => shouldFail ? reject(new Error('Network down')) : resolve(['HTML', 'CSS', 'JavaScript']), 1000);
        });
      }
      const o = document.getElementById('o');
      async function load(fail) {
        o.textContent = 'Loading...';
        try {
          const items = await fakeFetch(fail);
          o.innerHTML = items.map(i => '<li>' + i + '</li>').join('');
        } catch (e) {
          o.textContent = 'Error: ' + e.message;
        }
      }
      document.getElementById('ok').onclick = () => load(false);
      document.getElementById('bad').onclick = () => load(true);
    </script>

    Sending data with POST

    const response = await fetch("https://example.com/api/messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: "Sara", text: "Hello" })
    });
    const result = await response.json();
    console.log(result);

    Doing several requests together

    const [users, posts] = await Promise.all([
      fetch("/api/users").then(r => r.json()),
      fetch("/api/posts").then(r => r.json())
    ]);

    Promise.all starts both requests at once and waits until both finish, which is much faster than awaiting them one after the other. If any one fails, the whole thing rejects.

    CORS and keys

    • CORS: browsers only let your page read data from another site if that site agrees. If you see a CORS error, the API owner must allow it, or the request must go through your own server.
    • API keys identify you. Never put a secret key in front-end code, because every visitor can read it. Use a server (or a serverless function) to hold secrets.
    • Rate limits: free APIs allow only so many requests. Cache results, for example in localStorage, and avoid fetching on every keystroke.
    Common mistake

    Forgetting await before response.json(). You then get a Promise object instead of your data, and data.name is undefined. Also remember: fetch only rejects on network failure. A 404 still “succeeds”, so check response.ok.

    Read the API documentation

    Every API explains its addresses (endpoints), what parameters it accepts and what JSON it returns. Open an endpoint address in your browser tab first, to see the data with your own eyes, before writing any code.

    Check what you learned

    Five quick questions. Pick an answer and you will see straight away whether it is right and why.

    What is a Promise?

    1. A loop
    2. A CSS rule
    3. A variable type for numbers
    4. An object representing a future result

    It is pending, fulfilled or rejected.

    What does await do?

    1. Freezes the whole page
    2. Pauses the async function until the promise settles
    3. Deletes the promise
    4. Repeats the code

    Only that function waits.

    Does fetch reject on a 404 response?

    1. Yes
    2. Only on 500
    3. No, you must check response.ok
    4. Only offline

    A 404 still resolves.

    Why should you handle loading and error states?

    1. Visitors need feedback while waiting or when something fails
    2. It is faster
    3. It is required by CSS
    4. It hides data

    Blank screens confuse people.

    Where should secret API keys be kept?

    1. In front-end JavaScript
    2. In HTML comments
    3. On a server
    4. In localStorage

    Front-end code is visible to everyone.

    Summary

    • fetch returns a promise.
    • async/await makes asynchronous code readable.
    • Check response.ok and use try/catch.
    • Never put secret keys in front-end code.

    Next lesson

    Next: the intermediate project, building a to-do app that saves its data.

    Questions

    What is the difference between then and await?

    They do the same job. await is easier to read and works with try/catch.

    Why do I get a CORS error?

    The other server does not allow your site to read its data. Use an API that supports CORS or call it from your own server.

    Is there a free API to practise with?

    Yes. JSONPlaceholder, the PokeAPI and Open-Meteo are popular for learning.

    Progress is saved in this browser.