JavaScript · 3 minute lesson
Web applications often request data after the initial page has loaded. The Fetch API returns a Promise representing a request. Inside an async function, await lets you work with that Promise using a readable sequence of steps: request the resource, inspect the response, then read its body.
Always check the HTTP response status. Fetch does not reject its Promise simply because the server returns a status such as 404. The response.ok property helps you detect unsuccessful HTTP responses before trying to use the returned data.
A useful interface plans for three outcomes: loading, success, and failure. Show users a clear message when data is unavailable, and avoid leaving an empty area with no explanation. The example expects a JSON file at the stated path; substitute a resource that actually exists in your own project.
Try the example
async function loadLessons() {
try {
const response = await fetch("/lessons.json");
if (!response.ok) throw new Error("Request failed");
const lessons = await response.json();
console.log(lessons);
} catch (error) {
console.error("Could not load lessons:", error);
}
}Practice
Create a small JSON file in a local web project and load it with fetch. Then request a missing filename. Confirm that the failure path runs and decide what message your interface should show.
Continue learning: Official documentation.