Home >Web Front-end >JS Tutorial >Why Does `response.json()` Return a Promise in Fetch, and How Can I Access the Result?

Why Does `response.json()` Return a Promise in Fetch, and How Can I Access the Result?

DDD
DDDOriginal
2024-12-15 17:24:13928browse

Why Does `response.json()` Return a Promise in Fetch, and How Can I Access the Result?

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:

  • Why does response.json return a promise?

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.

  • Why does returning the promise from .then() provide the value?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn