Insight into Promises and Promise Chaining in Fetch Response Handling
While experimenting with the fetch() API, an intriguing observation emerged regarding the behavior of .json().
Observation:
When returning response.json() within an object literal passed to .then(), a Promise object is obtained. However, when returned directly from the .then() handler, it returns the actual value.
Explanation:
Calling response.json retrieves another promise for the HTTP response body, which is not yet loaded. This is because you receive the response object as soon as headers are received, but the body is not yet available.
This is a fundamental aspect of promises. Promises allow for chainability without nesting by enabling the return of promises from callback functions and their subsequent adoption.
Alternative Approaches:
To access the response status after awaiting the JSON body, you can adopt different approaches:
Return intermediate results using nested .then() chains:
Utilize async functions and await:
Caution:
It's always advisable to verify response status before accessing response content, as it may not always contain JSON data.
The above is the detailed content of Why Does `response.json()` Return a Promise in Fetch, and How Can I Access the Result?. For more information, please follow other related articles on the PHP Chinese website!