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.
Welcome back!
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.
- 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.
- C
- B
- A
- 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.
- 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).
- pending
- fulfilled
- rejected
- .then()
- .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);
}
}asyncbefore a function means it always returns a promise.awaitpauses 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:
- You need a second step,
await response.json(), to read the body as data. - 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
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.
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());
``
Lesson complete!