How does the fetch API work in JavaScript?
Fetch takes a URL and returns a promise that resolves with a Response object. The request is sent in the background, so the calling code continues immediately and handles the outcome later. Because the request itself is asynchronous, the promise almost always resolves with the response headers first, and you read the body separately.
// The Response object is what fetch resolves with.
// You can build one locally to try this without a network.
const response = new Response(JSON.stringify({ name: "Ada", id: 7 }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
async function readProfile() {
// A real call would be: const response = await fetch("/api/profile");
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
readProfile()
.then((profile) => console.log(profile.name, profile.id))
.catch((err) => console.log("failed:", err.message));Two parts of the API trip people up on their first use. The body has to be read explicitly, and you read it exactly once, with the method that matches its type: the json method for JSON, the text method for text, and the blob or arrayBuffer methods for binary data. The body is a stream, so reading it twice fails.
The second is the options object. It carries the method, the headers, the body and the credentials mode, and for anything other than a simple GET request the body has to be a string, a URL encoded form, a Blob or an array buffer. Sending an object does not serialise it for you; you have to call the json method on the request options or stringify it yourself.
Fetch also supports an abort signal, which is how you cancel a request that is no longer needed. Creating an abort controller and aborting it makes the fetch promise reject with an abort error, and the browser also stops the network request rather than just ignoring the result.