Loading
0xC0Lesson 13 of 16

Waiting for data: promises and fetch

Handle delayed results and distinguish a network failure from an HTTP error.

21 min 2-question quiz 1 code exercise
By the end of this lesson you can
  • Explain what a Promise represents
  • Use async and await with try/catch
  • Check response.ok before reading JSON

A network request takes time. A Promise represents a result that will arrive later or fail. An async function returns a Promise, and await pauses that function until the result settles. The rest of the page can keep responding while it waits.

promise.mjs
1async function loadCount() {
2  const count = await Promise.resolve(3);
3  return count + 1;
4}
5console.log(await loadCount());
Output
4

Try it

Up to 15 XP

Follow a data request

Step through the browser, server and page update. Predict when the data becomes available.

Message 1 of 5Predicted 0/0
Browser code
fetch
Server
Page
products.js
1async function showProducts() {
2  const status = document.querySelector("#status");
3  status.textContent = "Loading…";
4  try {
5    const response = await fetch("/api/products");
6    if (!response.ok) throw new Error("HTTP " + response.status);
7    const products = await response.json();
8    status.textContent = products.length + " products ready";
9  } catch {
10    status.textContent = "Could not load products. Try again.";
11  }
12}

A 404 or 500 response usually fulfills the fetch Promise; check response.ok. A network failure rejects it. This course runner blocks network requests, so the coding exercise uses a small Promise-based mock. See MDN network requests and fetch.

Key takeaways

  • await waits inside an async function for a Promise to settle.

  • Check response.ok for HTTP errors and catch network or parsing failures.

  • Show loading, success and failure states to the person using the page.

Lesson quiz

2 questions · pass with 2 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write JavaScript

Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.

Exercise 1

Handle an API result

+25 XP

The exercise provides a mock async request. Await it and print Loaded N products if ok is true, otherwise Could not load products. Input is ok,count or error,count. The runner awaits your async code; no real network is used.

  • Success
  • HTTP error
main.js
Loading editor…

JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…