Understanding the fetch() Function in JavaScript¶
The fetch() function is used to make network requests and retrieve resources from a server. It returns a Promise that resolves with a Response object representing the entire HTTP response.
Making a Request with fetch()¶
import fetch from "node-fetch";
fetch("https://www.boredapi.com/api/activity")
.then(response => {
// The response is a Response object
console.log(response);
return response.json(); // Parse the JSON in the response body
})
.then(data => {
// Data is the parsed JSON object from the response body
console.log(data);
});```
Handling the Response Object
• The Response object includes methods like json() to extract the body content.
• It contains properties such as status and ok.
Error Handling
• The Promise from fetch() will not reject due to HTTP errors like 404 or 500.
• It resolves normally with the ok property set to false for non-2xx responses.
if (response.ok) { // If HTTP status is 200-299, parse the JSON let json = await response.json(); } else { // Handle HTTP errors alert("HTTP-Error: " + response.status); }```
Stream Consumption • The body of a Response object is a stream and can only be read once.
• Calling response.text() consumes the body, so response.json() will fail afterward.
let text = await response.text(); // Consumes the response body let parsed = await response.json(); // This will fail
Asynchronous Reading • Methods like json() return a Promise because reading the stream is asynchronous.
• The first .then() handles the Response object, and the second .then() handles the parsed JSON data.
Fetch API in JavaScript¶
The fetch() function is used to make network requests and retrieve resources. It returns a Promise that resolves with a Response object.
Process Breakdown¶
Initial Fetch Request¶
When fetch(url) is called, it returns a Promise that resolves with a Response object once the server responds.
fetch(url)
.then(response => {
// Handle the Response object
});```
- First .then() - Accessing the Stream
The Response object has methods like json(), which reads the stream and parses the body text as JSON. This returns a Promise due to the asynchronous nature of stream reading.
- Second .then() - Handling the Parsed Data The Promise returned by response.json() resolves with the parsed JSON data. The second .then() handles this resolved Promise.
fetch(url) .then(response => response.json()) // Gets the Promise of the parsed JSON .then(data => { console.log(data); // Handles the resolved Promise with JSON data });
Summary The first .then() is for handling the Response object and calling json() to parse the stream. The second .then() handles the JSON data. This allows for a clean and manageable asynchronous code flow.