From Zero to Senior · The LabالعربيةGitHub

Chapter 13

Asynchronous JavaScript and fetch

5 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • understand why some work in JavaScript happens “later”
  • use timers, promises, async and await
  • load JSON data from a server with fetch
  • handle errors with try and catch, and show loading and error states
  • make the shop load its products from the server

Examples

13.1 Now and later

Run this program and look carefully at the order of the output:

timers.js⤓ File
console.log("1. Order placed");

setTimeout(() => {
  console.log("3. Food delivered!");
}, 1000);

console.log("2. Reading a book while waiting");
Recorded output$ node timers.js
1. Order placed
2. Reading a book while waiting
3. Food delivered!

13.2 Promises, async and await

Modern JavaScript makes promises easy to use with two words. A function marked async can use await, which pauses that function until a promise is ready, without freezing anything else:

promise.js⤓ File
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function makeTea() {
  console.log("Boiling the water…");
  await wait(300);
  console.log("Steeping the tea…");
  await wait(300);
  console.log("Done.");
  return "A cup of tea";
}

makeTea().then((result) => console.log(result));
console.log("Meanwhile, I set the table.");
Recorded output$ node promise.js
Boiling the water…
Meanwhile, I set the table.
Steeping the tea…
Done.
A cup of tea

13.3 fetch: asking a server for data

fetch(url) sends an HTTP request, exactly like the ones you read in Chapter 4, and returns a promise of the response. To make the example run anywhere, even without the internet, it starts its own small API server first:

fetch.js⤓ File
Runs with Node.js: node fetch.js
const http = require("node:http");

// A tiny API server with one address, /api/products
const products = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
];
const server = http.createServer((request, response) => {
  if (request.url === "/api/products") {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify(products));
  } else {
    response.writeHead(404);
    response.end();
  }
});

// The client code: this is what runs in a real app
async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}

server.listen(3001, async () => {
  const list = await getJson("http://localhost:3001/api/products");
  console.log(list.length, list[0].name);

  try {
    await getJson("http://localhost:3001/api/missing");
  } catch (error) {
    console.log("Could not load:", error.message);
  }

  server.close();
});
Recorded output$ node fetch.js
3 Code from Zero
Could not load: HTTP 404

13.5 Project: the shop loads its products

The shop from Chapter 12 had its products written inside shop.js. Real shops get them from a server, so that the owner can change products without touching the code. Let us move them into a JSON file next to the page:

products.json⤓ File
[
  {
    "id": 1,
    "name": "Code from Zero",
    "price": 25
  },
  {
    "id": 2,
    "name": "Bit mug",
    "price": 8
  },
  {
    "id": 3,
    "name": "Bit sticker",
    "price": 3
  },
  {
    "id": 4,
    "name": "Bit T-shirt",
    "price": 15
  },
  {
    "id": 5,
    "name": "Bit cap",
    "price": 12
  }
]

Now catalog starts empty, and a new start function loads the data and shows the three states. Here is the new end of shop.js; the rest of the file is unchanged from Chapter 12:

shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="shop.css">
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section>
        <p id="status" role="status"></p>
        <div id="products"></div>
      </section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
Figure 13.1: The shop now shows the five products from products.json, including the new cap.
+ 2 files
shop.css⤓ File
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #f5f5fb; color: #1e1b2e; }
header { padding: 16px 24px; color: white; background: #4338ca; }
header h1 { margin: 0; }
main { display: grid; grid-template-columns: 1fr 240px; gap: 16px; padding: 16px 24px; }
#products { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; align-content: start; }
.card { background: white; border-radius: 14px; padding: 14px; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card p { margin: 0 0 10px; color: #db2777; font-weight: 700; }
.card button { width: 100%; padding: 8px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
#cart { background: white; border-radius: 14px; padding: 4px 16px 12px; align-self: start; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
#cart-lines { padding: 0; list-style: none; }
#cart-lines li { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid #eef2ff; }
#cart-total { font-weight: 700; font-size: 1.2rem; color: #4338ca; }
@media (max-width: 560px) { main { grid-template-columns: 1fr; } }
#status { font-weight: 700; color: #4338ca; margin: 0 0 8px; }
#status:empty { display: none; }
shop.js⤓ File
let catalog = [];

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

// Load the products from the server, then draw the page
async function start() {
  const status = document.querySelector("#status");
  status.textContent = "Loading products…";
  try {
    const response = await fetch("products.json");
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    catalog = await response.json();
    status.textContent = "";
    renderProducts();
    renderCart();
  } catch (error) {
    status.textContent = "Sorry, the products could not be loaded. Please try again.";
    console.error(error);
  }
}

start();

Practice projects

Project 13.1 · Easy

A countdown that waits politely

Count down from 3 with a pause between numbers, then say “Go!”, and discover what the rest of the program does while it waits.

You will practise: wrapping setTimeout in a promise, await inside a loop, and the order in which async code runs.

Steps
  1. Copy the wait(ms) helper from this chapter: it returns a promise that resolves after ms milliseconds.
  2. Write async function countdown(from) with a for loop that prints n, then await wait(200).
  3. After the loop, print “Go!”.
  4. Call countdown(3), and on the next line print “Get ready…”.
  5. Before you run it, guess the order of the lines. Then run it and explain the surprise in one sentence.

Hint: an async function runs until its first await, then hands control back. That is why “Get ready…” sneaks in after the 3.

Solution
countdown.js⤓ File
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function countdown(from) {
  for (let n = from; n > 0; n--) {
    console.log(n + "…");
    await wait(200);
  }
  console.log("Go!");
}

countdown(3);
console.log("Get ready…");
Recorded output$ node countdown.js
3…
Get ready…
2…
1…
Go!

Project 13.2 · Medium

Breakfast: one by one, or all at once?

Make tea, toast and eggs, first one after another and then all at the same time, and measure the difference.

You will practise: functions that return values through promises, Promise.all, and timing code with Date.now().

Steps
  1. Write async function make(item, ms) that waits ms and returns item.
  2. Write seconds(start): the time since start, rounded to one decimal place.
  3. One after another: await the three dishes in turn (300, 400 and 500 ms) and print the time.
  4. All at once: start all three inside Promise.all([…]), await it, and print the time again.
  5. Promise.all gives back an array of results in the same order. Print them joined with " + ".

Hint: one by one takes the sum of the times; all at once takes only the longest. When a page needs three independent pieces of data, load them together.

Solution
breakfast.js⤓ File
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function make(item, ms) {
  await wait(ms);
  return item;
}

function seconds(start) {
  const ms = Date.now() - start;
  return (Math.round(ms / 100) / 10).toFixed(1);
}

async function main() {
  let start = Date.now();
  await make("tea", 300);
  await make("toast", 400);
  await make("eggs", 500);
  console.log("One after another:", seconds(start), "seconds");

  start = Date.now();
  const breakfast = await Promise.all([
    make("tea", 300),
    make("toast", 400),
    make("eggs", 500),
  ]);
  console.log("All at once:", seconds(start), "seconds");
  console.log(breakfast.join(" + "));
}

main();
Recorded output$ node breakfast.js
One after another: 1.2 seconds
All at once: 0.5 seconds
tea + toast + eggs

Project 13.3 · Challenge

A weather report that does not break

Ask a small weather API about three cities, one of which does not exist, and finish the report anyway.

You will practise: fetch, checking response.ok, throwing your own errors, and try/catch inside a loop.

Steps
  1. Build the tiny server the same way as in section 13.3: /api/weather/cairo returns JSON, and an unknown city returns 404.
  2. Reuse getJson(url): it throws an Error when response.ok is false.
  3. Write async function report(names): print a loading message, then loop over the names and await each city.
  4. Put the try/catch inside the loop, so one bad city prints “no data” and the loop carries on.
  5. Print a final line so the user knows the report is complete. Then try moving the try outside the loop and see what is lost.

Hint: where you put try decides how much one failure can break. Around the whole loop, one bad city stops everything; around each request, it costs only one line.

Solution
weather.js⤓ File
Runs with Node.js: node weather.js
const http = require("node:http");

// A tiny weather API: /api/weather/cairo and so on
const weather = {
  cairo: { city: "Cairo", temp: 31, sky: "sunny" },
  dubai: { city: "Dubai", temp: 35, sky: "very hot" },
  london: { city: "London", temp: 14, sky: "light rain" },
};
const server = http.createServer((request, response) => {
  const name = request.url.replace("/api/weather/", "");
  if (weather[name]) {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify(weather[name]));
  } else {
    response.writeHead(404);
    response.end();
  }
});

// The client code
async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}

async function report(names) {
  console.log("Loading the weather…");
  for (const name of names) {
    try {
      const day = await getJson(`http://localhost:3002/api/weather/${name}`);
      console.log(`${day.city}: ${day.temp}°C, ${day.sky}`);
    } catch (error) {
      console.log(`${name}: no data (${error.message})`);
    }
  }
  console.log("Report finished.");
}

server.listen(3002, async () => {
  await report(["cairo", "atlantis", "london"]);
  server.close();
});
Recorded output$ node weather.js
Loading the weather…
Cairo: 31°C, sunny
atlantis: no data (HTTP 404)
London: 14°C, light rain
Report finished.

Exercises

Exercise 13.1 · Easy

Write a countdown that prints 3, 2, 1, “Go!”, one line per second, using async, await and the wait function.
The book's short answer
for (const n of [3, 2, 1]) { console.log(n); await wait(1000); } console.log("Go!"); inside an async function.
Show the solution
countdown.js⤓ File
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function countdown() {
  for (const n of [3, 2, 1]) {
    console.log(n);
    await wait(1000); // the loop pauses here for one second, without freezing the program
  }
  console.log("Go!");
}

countdown();
Recorded output$ node countdown.js
3
2
1
Go!

Exercise 13.2 · Easy

In fetch.js, add a second address, /api/hello, that returns {"message": "Hi!"}, and fetch it.
The book's short answer
Add else if (request.url === "/api/hello") that sends JSON.stringify({ message: "Hi!" }).
Show the solution
fetch.js⤓ File
Runs with Node.js: node fetch.js
const http = require("node:http");

// fetch.js from the chapter, with a second address: /api/hello
const products = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
];
const server = http.createServer((request, response) => {
  if (request.url === "/api/products") {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify(products));
  } else if (request.url === "/api/hello") {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify({ message: "Hi!" }));
  } else {
    response.writeHead(404);
    response.end();
  }
});

async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}

server.listen(3021, async () => {
  const list = await getJson("http://localhost:3021/api/products");
  console.log(list.length, list[0].name);

  const hello = await getJson("http://localhost:3021/api/hello");
  console.log(hello);
  console.log(hello.message);

  server.close();
});
Recorded output$ node fetch.js
3 Code from Zero
{ message: 'Hi!' }
Hi!

Exercise 13.3 · Medium

Add a “Reload” button to the shop that appears with the error message and calls start() again.
The book's short answer
Show a button in the catch block; its click handler calls start().
Show the solution
shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="../../examples/shop.css">
    <style>
      #reload { margin-top: 8px; padding: 6px 16px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
    </style>
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section>
        <p id="status" role="status"></p>
        <button id="reload" type="button" hidden>Reload</button>
        <div id="products"></div>
      </section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ File
let catalog = [];

// Open the page as shop.html?fail to make the first load fail on purpose, and test the Reload button.
let failOnce = location.search.includes("fail");
const reload = document.querySelector("#reload");
reload.addEventListener("click", () => start());

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  container.replaceChildren();
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

// Load the products from the server, then draw the page
async function start() {
  const status = document.querySelector("#status");
  status.textContent = "Loading products…";
  reload.hidden = true;
  try {
    const response = await fetch(failOnce ? "missing.json" : "../../examples/products.json");
    failOnce = false;
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    catalog = await response.json();
    status.textContent = "";
    renderProducts();
    renderCart();
  } catch (error) {
    status.textContent = "Sorry, the products could not be loaded. Please try again.";
    console.error(error);
    // Show the button with the error message; clicking it simply runs start() again.
    reload.hidden = false;
  }
}

start();

Exercise 13.4 · Medium

Look up Promise.all on MDN. Use it to fetch two JSON files at the same time and print both results.
The book's short answer
const [a, b] = await Promise.all([getJson(url1), getJson(url2)]);
Show the solution
promise-all.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Promise.all</title>
    <style>body { font-family: system-ui, sans-serif; margin: 24px; } pre { background: #f5f5fb; padding: 12px; border-radius: 8px; }</style>
  </head>
  <body>
    <h1>Promise.all</h1>
    <p>Two JSON files, loaded at the same time:</p>
    <pre id="out">…</pre>
    <script>
      async function getJson(url) {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json();
      }

      async function main() {
        const [products, settings] = await Promise.all([
          getJson("../../examples/products.json"),
          getJson("settings.json"),
        ]);
        document.querySelector("#out").textContent =
          JSON.stringify(products, null, 2) + "\n\n" + JSON.stringify(settings, null, 2);
      }

      main().catch((error) => {
        document.querySelector("#out").textContent = `Could not load: ${error.message}`;
      });
    </script>
  </body>
</html>
promise-all.html640px
promise-all.js⤓ File
Runs with Node.js: node promise-all.js
const http = require("node:http");

// Two JSON files, served by a tiny server so fetch can load them.
const files = {
  "/products.json": [{ id: 1, name: "Bit mug", price: 8 }],
  "/weather.json": { city: "Alexandria", temperature: 24 },
};
const server = http.createServer((request, response) => {
  // Each answer takes 500 ms, to show that both requests wait at the same time.
  setTimeout(() => {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify(files[request.url]));
  }, 500);
});

async function getJson(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

server.listen(3022, async () => {
  const started = Date.now();
  const [products, weather] = await Promise.all([
    getJson("http://localhost:3022/products.json"),
    getJson("http://localhost:3022/weather.json"),
  ]);
  console.log(products);
  console.log(weather);
  // About 0.5 s, not 1 s: the two requests ran side by side.
  console.log(`Both arrived in about ${Math.round((Date.now() - started) / 100) / 10} s`);
  server.close();
});
Recorded output$ node promise-all.js
[ { id: 1, name: 'Bit mug', price: 8 } ]
{ city: 'Alexandria', temperature: 24 }
Both arrived in about 0.5 s
settings.json⤓ File
{ "theme": "dark", "language": "en", "currency": "USD" }

Exercise 13.5 · Challenge

Use the free public API at https://api.github.com/users/ followed by a username to build a page that shows a GitHub user’s name, picture and number of public repositories. Handle the “user not found” case.
The book's short answer
Fetch `https://api.github.com/users/${name}`, check response.status === 404 for “not found”, and show name, avatar_url and public_repos.
Show the solution
github-user.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>GitHub user</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; max-width: 520px; }
      form { display: flex; gap: 8px; }
      input, button { font: inherit; padding: 8px 12px; border-radius: 8px; border: 1px solid #c7c5d9; }
      button { color: white; background: #1e1b2e; border: 0; cursor: pointer; }
      .card { display: flex; gap: 16px; align-items: center; margin-top: 20px; padding: 16px; border-radius: 14px; background: #f5f5fb; }
      .card img { border-radius: 50%; }
      .error { color: #b91c1c; font-weight: 700; }
      .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
    </style>
  </head>
  <body>
    <h1>Find a GitHub user</h1>
    <form id="form">
      <label for="name" class="visually-hidden">Username</label>
      <input id="name" value="octocat" required>
      <button>Show</button>
    </form>
    <div id="result" role="status"></div>
    <script>
      const result = document.querySelector("#result");

      async function showUser(name) {
        result.textContent = "Loading…";
        try {
          const response = await fetch(`https://api.github.com/users/${encodeURIComponent(name)}`);
          // 404 is not an exception for fetch: the request worked, the user does not exist.
          if (response.status === 404) {
            result.innerHTML = "";
            const p = document.createElement("p");
            p.className = "error";
            p.textContent = `No user called "${name}".`;
            result.append(p);
            return;
          }
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
          }
          const user = await response.json();

          const card = document.createElement("div");
          card.className = "card";
          const img = document.createElement("img");
          img.src = user.avatar_url;
          img.alt = "";
          img.width = 80;
          img.height = 80;
          const text = document.createElement("div");
          const title = document.createElement("h2");
          title.textContent = user.name || user.login;
          const repos = document.createElement("p");
          repos.textContent = `Public repositories: ${user.public_repos}`;
          text.append(title, repos);
          card.append(img, text);
          result.replaceChildren(card);
        } catch (error) {
          // No network, or too many requests (GitHub allows 60 an hour without signing in).
          result.innerHTML = `<p class="error">Could not load the user. Try again later.</p>`;
          console.error(error);
        }
      }

      document.querySelector("#form").addEventListener("submit", (event) => {
        event.preventDefault();
        showUser(document.querySelector("#name").value.trim());
      });

      showUser("octocat");
    </script>
  </body>
</html>
github-user.html640px