Nishaglobal Education logo

Timers, promises and loading data with fetch

Understand asynchronous JavaScript: setTimeout, promises and async/await, then load JSON data from the web with fetch, show loading and error states, and handle failures with try/catch.

Lesson 13 of 1345 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Explain why some code finishes later, using setTimeout
  • Load JSON data with fetch, async and await
  • Show loading and error states and handle failed requests
Outline
  1. What you'll learn and why it matters
  2. Doing something later: setTimeout
  3. Loading data with fetch
  4. When things go wrong
  5. Showing data on the page, with loading and error states
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

What you'll learn and why it matters

Some jobs take time: waiting for a timer, or asking a server for data on the other side of the world. JavaScript does not freeze the page while it waits. It starts the job, carries on, and comes back when the result arrives. This is called asynchronous code, and it is how every app loads posts, prices, weather and search results.

Doing something later: setTimeout

JavaScript
console.log("1. Order placed");

setTimeout(() => {
  console.log("3. Chai is ready!");
}, 2000);

console.log("2. Please wait…");

Console (Chrome and Edge)

1. Order placed
2. Please wait…
3. Chai is ready!

setTimeout(function, 2000) runs the function after about 2000 milliseconds (2 seconds). Notice the order: line 2 prints before line 3, even though it comes later in the file. JavaScript did not wait; it scheduled the function and moved on.

time0 msfetch(url) sends the request1 msother code keeps running…the page still scrolls and clicks~300 msthe response arrivescode after await runs with the data
A timeline. JavaScript sends a request and immediately continues running other code, so the page stays responsive. Later the response arrives, and the code after await, or in then, runs with the data.

Loading data with fetch

fetch(url) asks a server for a file or data. We have put a small menu in JSON format on this website for you to practise with. It is safe to load from your own pages, even ones opened straight from a folder:

AddressContains
https://www.nishaglobaleducation.com/downloads/courses/web/menu.jsonA café name and a list of menu items, each with a name, price and category
JavaScript
async function loadMenu() {
  const response = await fetch("https://www.nishaglobaleducation.com/downloads/courses/web/menu.json");
  const data = await response.json();
  console.log(data.cafe);
  console.log(`${data.items.length} items`);
  console.log(data.items[0].name);
}

loadMenu();

Console (Chrome and Edge)

Green Leaf Café
4 items
Masala chai
PieceMeaning
async functionA function that is allowed to wait for slow jobs inside it
await fetch(url)Send the request and wait here (without freezing the page) for the response
await response.json()Wait for the body to download and turn the JSON text into JavaScript objects

When things go wrong

Networks fail: no signal, a wrong address, a server error. Two kinds of failure need handling:

ProblemWhat fetch doesHow to catch it
No connection, blocked requestThe promise fails (throws an error)try { … } catch (error) { … }
Server answers with an error such as 404 Not FoundSucceeds, but response.ok is falseCheck response.ok and response.status
JavaScript
async function loadJson(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.log(`Could not load data. ${error.message}`);
    return null;
  }
}

async function main() {
  const missing = await loadJson("https://www.nishaglobaleducation.com/downloads/courses/web/no-such-file.json");
  console.log(missing);
  const menu = await loadJson("https://www.nishaglobaleducation.com/downloads/courses/web/menu.json");
  console.log(menu.items.length);
}

main();

Console (Chrome and Edge)

Could not load data. Request failed: 404
null
4

throw new Error(…) creates an error on purpose, which jumps straight to catch. One catch then handles every kind of failure in one place.

Showing data on the page, with loading and error states

Put it together with the render pattern from lesson 11. Always tell people what is happening: *Loading…* while waiting, the data when it arrives, and a helpful message if it fails.

JavaScript
const status = document.querySelector("#status");
const list = document.querySelector("#menu-list");

async function showMenu() {
  status.textContent = "Loading the menu…";
  try {
    const response = await fetch("https://www.nishaglobaleducation.com/downloads/courses/web/menu.json");
    if (!response.ok) throw new Error(`Status ${response.status}`);
    const data = await response.json();

    for (const item of data.items) {
      const li = document.createElement("li");
      li.textContent = `${item.name}: ₹${item.price}`;
      list.append(li);
    }
    status.textContent = `${data.cafe}: ${data.items.length} items`;
  } catch (error) {
    status.textContent = "Sorry, the menu could not be loaded. Please try again later.";
    console.log(error.message);
  }
}

showMenu();
Show the HTML this script works with
<h2>Today's menu</h2>
<p id="status" aria-live="polite"></p>
<ul id="menu-list"></ul>

Live preview: try it

Console

Nothing logged yet.

Press Run again on the preview to watch it load. If you are offline, you will see the error message instead of a blank page.

Practice

Guided exercise

Average price

Load the menu JSON and print the average price of all items to 2 decimal places.

  1. Write async function averagePrice().
  2. await the fetch and await response.json().
  3. Use reduce to add up item.price, divide by the number of items, and print with toFixed(2).
  4. Call the function.
Show the solution
Solution
async function averagePrice() {
  const response = await fetch("https://www.nishaglobaleducation.com/downloads/courses/web/menu.json");
  const data = await response.json();
  const total = data.items.reduce((sum, item) => sum + item.price, 0);
  console.log(`Average price: ₹${(total / data.items.length).toFixed(2)}`);
}

averagePrice();

Console (Chrome and Edge)

Average price: ₹43.75

How to get there: Once the JSON is parsed it is ordinary JavaScript data, so the array methods from lesson 7 work as usual. (40 + 50 + 60 + 25) / 4 = 43.75.

Your turn

Drinks only, on the page

Load the menu and show only the drinks as list items in #drinks. Show Loading… in #status first, and an error message if loading fails.

Show the solution
Solution
const status = document.querySelector("#status");
const list = document.querySelector("#drinks");

async function showDrinks() {
  status.textContent = "Loading…";
  try {
    const response = await fetch("https://www.nishaglobaleducation.com/downloads/courses/web/menu.json");
    if (!response.ok) throw new Error(`Status ${response.status}`);
    const data = await response.json();
    const drinks = data.items.filter((item) => item.category === "drinks");

    for (const drink of drinks) {
      const li = document.createElement("li");
      li.textContent = drink.name;
      list.append(li);
    }
    status.textContent = `${drinks.length} drinks`;
  } catch {
    status.textContent = "Sorry, the drinks could not be loaded.";
  }
}

showDrinks();
Show the HTML this script works with
<p id="status" aria-live="polite"></p>
<ul id="drinks"></ul>

Live preview: try it

Console

Nothing logged yet.

How to get there: Load, check response.ok, parse, filter, render, then update the status. The catch makes sure people see a message rather than an empty list if anything fails.

Common mistakes

Forgetting await before fetch or response.json()

You see: You log Promise {<pending>} instead of data

Fix: Put await before each slow step, inside an async function.

Using await outside an async function

You see: SyntaxError: await is only valid in async functions and the top level bodies of modules

Fix: Wrap the code in an async function and call it.

Not checking response.ok

You see: A 404 error page is treated as data, then response.json() fails

Fix: Throw an error when !response.ok.

No loading or error message

You see: People see a blank area and think the page is broken

Fix: Show *Loading…* first and a friendly message in catch.

Fetching a local file from a page opened as file://

You see: A CORS or *Failed to fetch* error

Fix: Use a web address, or run a local server such as Live Server.

Recap

  • Asynchronous code starts a slow job and carries on; setTimeout shows the order clearly.
  • In an async function, await fetch(url) then await response.json() loads JSON data.
  • Handle failures with try/catch and check response.ok for server errors.
  • Always show loading and error states; use the Network tab to debug requests.

Key terms

Asynchronous
Code that finishes later, while the rest of the program keeps running.
Promise
An object representing a result that will be ready in the future.
fetch
A browser function that requests data or files over the network.
API
A way for programs to talk to each other, often by requesting JSON data from a web address.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. In what order are these printed? console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C");

  2. 2. What does `await response.json()` give you?

  3. 3. fetch returns a response with status 404. What happens without a response.ok check?

  4. 4. Where can you use the await keyword in a normal script?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.