Why does .json() Return a Promise, but Not When It Passes Through .then()?
Question:
While using the Fetch API, it's observed that the .json() method returns a Promise object when used within an object literal in a .then() handler. However, when used without an object literal, it returns the value directly.
Answer:
Regarding Promises:
.json() returns a Promise because the HTTP response is received when the headers are available, but the body (in this case, JSON) is not yet loaded. .json() retrieves a second promise for the body, which must be loaded separately.
Regarding .then() Behavior:
When a Promise is returned from a .then() callback, it's adopted by the outer chain. This means that the outer .then() will receive the fulfilled value of the inner Promise. In the given example, the outer .then() receives an object with the data and status properties, effectively making the data property available directly within the .then().
Alternative Solutions:
To access both the status and JSON data directly within one .then() handler, you can use the following techniques:
fetch(url) .then(response => response.json()) .then(data => { console.log(response.status, data.title); });
const response = await fetch(url); const data = await response.json(); console.log(response.status, data.title);
Remember to verify the response status before reading the body, as it might not always contain JSON data.
The above is the detailed content of Why Does `fetch().then().json()` Sometimes Return a Promise and Sometimes Not?. For more information, please follow other related articles on the PHP Chinese website!