New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› JavaScript› Async JavaScript and APIs

Async JavaScript and APIs

💻 JavaScript

Fetch data from an API with promises and async/await, then handle errors.

Lesson 7 of 9 Tutorial
0 of 9 completed

Some work takes time: network requests, timers and file reads. Asynchronous code lets the page keep responding while it waits.

By the end of this lesson you can:
  • Explain a promise.
  • Use fetch with async/await.
  • Handle loading and error states.

Promises

A promise represents a value that will arrive later. It can be pending, fulfilled or rejected. fetch returns a promise.

Fetch with async/await

Mark the function async and use await to pause until the promise settles.

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

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

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

loadUsers();

Loading and Error States

A real interface shows a loading message, then either data or an error. Never leave the user staring at a blank screen.

const status = document.querySelector("#status");

async function loadPosts() {
  status.textContent = "Loading…";

  try {
    const response = await fetch("/api/posts");
    if (!response.ok) throw new Error("Server error");
    const posts = await response.json();
    status.textContent = `${posts.length} posts loaded`;
  } catch (error) {
    status.textContent = "Could not load posts. Please try again.";
  }
}
Tip Always check response.ok. fetch resolves even for a 404 or 500 response, so a missing check hides real errors.

Practice

  1. Fetch a list of posts and log the titles.
  2. Show a loading message while the request runs.
  3. Display a friendly error if the request fails.

Hands-on exercise

Write an async function that fetches https://jsonplaceholder.typicode.com/todos/1 and logs the title.
Handle errors with try/catch.

Recap

Promises represent future values. async/await makes them readable, and try/catch keeps failures from breaking the page.

Example

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

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

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

loadUsers();

Exercises

Exercise 1. Fetch and display Medium
Write an async function that fetches https://jsonplaceholder.typicode.com/todos/1 and logs the title.
Handle errors with try/catch.
JavaScript exercise-1.js
Expected Output
The title of the todo is printed to the console.

Lesson Nav

Lesson sections