Request
Describes what should be fetched.
fetch is the browser API for making HTTP requests from JavaScript.
const response = await fetch("/data.json");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
Async JavaScript
fetch returns a promise that resolves to a Response object. The promise rejects for network-level failures, not for every HTTP error status.
Always check response.ok or response.status before trusting the response body.
Reading the body is async too. Use response.json, response.text, response.blob or stream reading depending on the data.
Describes what should be fetched.
Contains status, headers and body readers.
True for status 200 through 299.
json, text, blob and stream access.
Examples
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const data = await fetch(url).then(response => response.json()); // What if the server returns 404 or HTML?
Code patterns
These examples are the async patterns you will reuse: timers, promises, composition, await, fetch and cancellation.
Request a resource.
const response = await fetch("/api/items");
HTTP 404 still resolves to a Response.
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
Body parsing is async.
const data = await response.json();
Set method, headers and body.
await fetch("/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
Rules that matter
Async JavaScript is easier when every operation has clear pending, success, failure and cancellation behavior.
HTTP error statuses do not always reject fetch.
Use json for JSON and text for text.
fetch can reject when the request cannot complete.
Content-Type matters when sending JSON.
Validate JSON before using it.
AbortController can stop requests that are no longer needed.
Production thinking
fetch is the main bridge between browser JavaScript and server data.
Fetched content should update visible loading, success and error messages.
Production fetch wrappers often centralize status checks, JSON parsing, timeout and reporting.
Important content loaded only through fetch may need server rendering or reliable fallback.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain when the code runs, how it fails and what happens if it becomes irrelevant, you understand the async model.