Async and fetch
Request data over the network without freezing the interface.
- Use async and await
- Check response.ok
- Handle loading and error states
Network requests take time. Promises let the browser keep painting while you wait. async/await makes that flow read like synchronous code.
async function loadCourses() {
try {
const response = await fetch("/api/courses");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const courses = await response.json();
return courses;
} catch (error) {
console.error("Could not load courses", error);
return [];
}
}- 01Start loading
Show a skeleton or spinner immediately so the interface never feels frozen.
- 02Await the response
fetch only rejects on network failure — check response.ok for 4xx and 5xx.
- 03Parse once
Call response.json() exactly once. The body stream can only be consumed once.
- 04Handle both paths
Render the data or a clear, actionable error. Never leave a permanent spinner.
Load and render
Write an async function that fetches /api/lessons, checks the response and returns the parsed JSON.
async function getLessons() {
// your code here
}Does fetch reject when the server returns 404?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.