Find a course

Module 5: Web Pages, Errors and Async CodeLesson 12 of 1214 min

Asynchronous JavaScript: Timers, Promises and fetch

Understand why JavaScript is asynchronous, use setTimeout, promises and async/await, and load data from a web API with fetch.

Step 1 of 15Learn

Waiting without freezing

When you order coffee, the barista doesn't stop serving everyone else while your drink brews. They take your order, give you a ticket, and call your name when it's ready. JavaScript works the same way.

JavaScript runs your code on a single thread: one thing at a time. If it stopped and waited every time it loaded data from a server, which can take seconds, the whole page would freeze. So slow operations are asynchronous: JavaScript starts them, continues with other work, and runs a callback when the result is ready.

The simplest example is a timer:

console.log("1: order placed");
setTimeout(() => {
  console.log("3: coffee ready");
}, 2000);
console.log("2: serving the next customer");

The output is 1, 2, 3, even though the setTimeout line comes second. setTimeout schedules the callback to run after at least 2,000 milliseconds and returns immediately, so line 2 runs first.

Even setTimeout(fn, 0) runs after the current code finishes, because scheduled callbacks wait in a queue until the call stack is empty. The mechanism that moves them from the queue to execution is called the event loop. Its key rule is easy to remember: synchronous code always finishes first; callbacks run later.

setInterval(fn, ms) repeats a callback every ms milliseconds until you stop it with clearInterval.

Step 2 of 15Practice · Diagram

What happens to a setTimeout callback

Where is a 0 ms timeout callback while the rest of your script is still running?

Tap the shape that answers the question, then press Check.

What happens to a setTimeout callbackProcess diagram: Your code runs top to bottom → Timer handed to the browser → Callback waits in a queue → Stack empty: callback runs.Your coderuns top tobottomTimer handedto thebrowserCallbackwaits in aqueueStack empty:callback runs
Your code runs top to bottom

One thing at a time on the single thread.

Timer handed to the browser

The browser counts down; JavaScript carries on.

Callback waits in a queue

Even with a delay of 0, it waits here.

Stack empty: callback runs

Only after all current code has finished.

Step 3 of 15Practice · Put in order

In what order are these messages logged? ``js console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C"); setTimeout(() => console.log("D"), 100); ``

Drag the items, or use the arrow buttons, to put them in order.

  1. C
  2. B
  3. A
  4. D

Step 4 of 15Learn

Promises

Callbacks work, but nesting several of them (load the user, then their orders, then each order's details) creates deeply indented, hard-to-read "callback pyramids." Promises were added to fix this.

A promise is an object representing a value that isn't available yet. It is always in one of three states:

  • pending: still working
  • fulfilled: finished successfully, with a value
  • rejected: failed, with an error

You attach handlers with .then for success and .catch for failure:

fetch("https://api.example.com/products")
  .then(response => response.json())
  .then(products => console.log(products.length))
  .catch(error => console.error("Failed:", error))
  .finally(() => console.log("Done"));

Each .then returns a new promise, so steps chain in a flat, readable sequence instead of nesting. A single .catch at the end handles an error from any step above it.

The value inside a promise can only be used in a handler (or with await, next). A very common mistake is const data = fetch(url); followed by console.log(data.length): data is the promise itself, not the products, so you get undefined. The data doesn't exist yet when that line runs.

Step 5 of 15Practice · Diagram

A promise settles only once

A network failure stops a fetch. Which state does the promise end in?

Tap the shape that answers the question, then press Check.

A promise settles only onceHierarchy diagram: pending, fulfilled → .then runs, rejected → .catch runs.pendingfulfilled → .then runsrejected → .catchruns
pending

The request is still in progress.

fulfilled → .then runs

Finished with a value, such as the response.

rejected → .catch runs

Failed with an error, such as a network failure.

Step 6 of 15Practice · Match the pairs

Match each promise state or method to its meaning.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. pending
  2. fulfilled
  3. rejected
  4. .then()
  5. .catch()

Step 7 of 15Learn

async and await

async/await is syntax built on promises that lets asynchronous code read like ordinary top-to-bottom code:

async function showProducts() {
  try {
    const response = await fetch("https://api.example.com/products");
    if (!response.ok) {
      throw new Error(`Server error: ${response.status}`);
    }
    const products = await response.json();
    console.log(`Loaded ${products.length} products`);
  } catch (error) {
    console.error("Could not load products:", error.message);
  }
}
  • async before a function means it always returns a promise.
  • await pauses that function until the promise settles, then gives you its value. The rest of the page keeps running meanwhile.
  • Errors from awaited promises are caught with an ordinary try...catch.

fetch is the built-in function for HTTP requests. It returns a promise for a Response object. Two details matter:

  1. You need a second step, await response.json(), to read the body as data.
  2. fetch only rejects on network failure. A 404 or 500 response still fulfills, so check response.ok (true for status codes 200–299) yourself.

await only works inside an async function (or at the top level of a JavaScript module). To run independent requests at the same time rather than one after another, start them together and wait with await Promise.all([fetch(a), fetch(b)]).

Step 8 of 15Note

Step 9 of 15Chart

Waiting for independent requests

Waiting for independent requestsBar chart with 4 categories: 1 request: await one after another 1 s, Promise.all 1 s; 2 requests: await one after another 2 s, Promise.all 1 s; 3 requests: await one after another 3 s, Promise.all 1 s; 4 requests: await one after another 4 s, Promise.all 1 s.0 s1 s2 s3 s4 sseconds1 request2 requests3 requests4 requests1 s1 s2 s1 s3 s1 s4 s1 s
Illustrative: each request takes about 1 second and none depends on another.
Waiting for independent requests
Itemawait one after anotherPromise.all
1 request1 s1 s
2 requests2 s1 s
3 requests3 s1 s
4 requests4 s1 s

Step 10 of 15Practice · Spot the mistake

This function should log the number of users from an API, but it logs undefined. Which line is wrong?

Step 11 of 15Note

Step 12 of 15Practice · Code challenge

response.ok is true when the HTTP status code is from 200 to 299. Write a function isOk(status) that returns true for those status codes and false for any other, so you can see exactly which responses count as success.

Runs in a sandbox in your browser.
  • isOk(200)
  • isOk(201)
  • isOk(299)
  • isOk(404)
  • isOk(300)
  • isOk(199)

Step 13 of 15Practice · True or false

fetch rejects its promise when the server responds with a 404 Not Found status.

Step 14 of 15Note

Step 15 of 15Practice · Choose one

What does this code log? ``js async function getNumber() { return 7; } console.log(getNumber()); ``