fetch, async/await & JSON
Load data with fetch
Lesson 13 of 20 · 12 min · Module 4: Talk to a server
Real pages get their data from a server: products, messages, lessons. fetch requests data from an address, and async/await lets you write the code in the order things happen.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Request data with fetch
- Read JSON responses
- Write asynchronous code with async and await
The idea
await fetch('/api/courses') waits for the server’s response, and await response.json() reads its body as JSON. Both steps are asynchronous, so they live in an async function. In this sandbox, a small sample server answers requests such as GET /api/courses; nothing leaves your computer.
async function loadUser() {
const response = await fetch('/api/user');
const user = await response.json();
console.log(user.name);
}
loadUser();
01Two steps, two awaits
fetch resolves as soon as the response headers arrive; the body may still be downloading. That is why reading it with response.json() is a second, separate await.
02Async functions return promises
Code after loadCourses() runs immediately, before the data arrives. Anything that needs the data belongs inside the async function, after the awaits.
loadCourses();
console.log('This prints first');This prints first03Data from servers is still user data
Course titles may have been typed by anyone with access to the server. Keep inserting them with textContent, exactly as you did with names and bios.
Your turn
async function loadCourses() that fetches /api/courses, reads the JSON array, and renders one <li> per course into #courses with the text HTML & CSS Foundations · 20 lessons. Show the number in #count as 3 courses (1 course for one). Then call the function.What the checks look for
- It requests /api/courses
- Every course is shown
- The number of courses is shown
- It works with other data
- Titles from the server stay plain text
Take this with you
fetch the response, await its JSON, then render.
Go a little further
Show the courses as cards built from a <template>, as in the templates lesson.