Waiting for data: promises and fetch
Handle delayed results and distinguish a network failure from an HTTP error.
- 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.
1async function loadCount() {
2 const count = await Promise.resolve(3);
3 return count + 1;
4}
5console.log(await loadCount());4
Try it
Up to 15 XPFollow a data request
Step through the browser, server and page update. Predict when the data becomes available.
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.
Handle an API result
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
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…