Module 2 ยท JavaScript in the browser Lesson 6 of 15
fetch, JSON and async
fetch asks a server for data without reloading the page. async/await is how you wait for the answer without freezing the interface.
The concept
fetch asks a server for data and returns a promise โ a value that will exist later. With async and await, asynchronous code reads like ordinary code: const res = await fetch(url); const data = await res.json();. JSON is the format that comes back: objects, arrays, strings and numbers, exactly like the dictionaries and lists you already know.
Three things to handle every time. Check res.ok before using the data, because a 404 or a 500 is not a JavaScript error and will not throw. Wrap it in try { โฆ } catch (e) { โฆ } so a dropped connection shows a message instead of a blank screen. And show a loading state: a user who sees nothing assumes the app is broken.
// The shape of every fetch: await, check ok, parse, catch.
const data = { jobs: [{ title: 'Data Analyst' }, { title: 'QA Engineer' }] };
async function loadJobs() {
// In a real app this line is: const res = await fetch('/api/jobs');
const res = { ok: true, json: async () => data };
if (!res.ok) throw new Error('Request failed: ' + res.status);
const json = await res.json();
return json.jobs;
}
loadJobs()
.then((jobs) => jobs.forEach((j) => console.log(j.title)))
.catch((e) => console.error('Could not load jobs: ' + e.message));Common mistakes
The mistake is a hardcoded URL such as http://localhost:3000/api/jobs โ fine on your laptop, dead for every visitor. Keep the API address in one place and choose it per environment, and you will not be the person who deploys a working app that fetches from nowhere.
Worked example
const res = await fetch("/api/jobs"); const jobs = await res.json(); โ forgetting the second await is the classic bug, and it fails silently.
Your practice task
Load a public JSON API, render the results into cards, and show a loading state and an error state separately.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
fetch asks a server for data and returns a promise โ a value that will exist later.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.