When working with the fetch() API, a subtle difference in behavior arises when using the .json() method. This behavior may seem counterintuitive, so let's delve into the underlying reasons.
By default, .json() returns a promise that resolves to the parsed JSON response body. This is because the response body may not be immediately available, especially for large responses or slow connections. The promise ensures that the subsequent code doesn't execute until the JSON is fully parsed.
When .json() is used within a .then() chain, it returns the promise object itself, allowing for chaining of further operations. However, when .json() is returned directly from the .then() handler, the resolved value of the promise (the parsed JSON) is returned instead. This is because the .then() handler expects to receive a value that can be further manipulated.
Example:
In the provided code snippet:
fetch(url) .then(response => { return { data: response.json(), status: response.status } }) .then(post => document.write(post.data));
The .json() method is chained within an object literal, so it returns a promise object, resulting in the post.data attribute being a Promise.
Alternative Syntax:
fetch(url) .then(response => response.json()) .then(post => document.write(post.title));
In this example, .json() is returned directly from the .then() handler, so the resolved JSON value is immediately returned, allowing for direct access to the post.title attribute.
To avoid the discrepancy between object literals and direct return values, you can use the following syntax:
fetch(url) .then(response => response.json().then(data => ({ data: data, status: response.status })
This approach returns a nested promise that ultimately resolves to the desired object.
The promise behavior of .json() depends on how it is used within the code. When chaining operations, it returns a promise object, ensuring proper sequencing. However, when returning .json() directly from a .then() handler, the resolved value (parsed JSON) is returned, allowing for immediate use. Understanding this difference is crucial for managing promises and avoiding unexpected behaviors in your code.
The above is the detailed content of Why Does Fetch API's `.json()` Method Have Different Promise Behaviors?. For more information, please follow other related articles on the PHP Chinese website!