Home > Web Front-end > JS Tutorial > Why Does Fetch API's `.json()` Method Have Different Promise Behaviors?

Why Does Fetch API's `.json()` Method Have Different Promise Behaviors?

Patricia Arquette
Release: 2024-12-31 19:08:12
Original
773 people have browsed it

Why Does Fetch API's `.json()` Method Have Different Promise Behaviors?

Promise Handling in Fetch API: Why .json() Behavior Differs

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.

Promise Nature of .json()

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.

Promise Chaining and Value Return

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));
Copy after login

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));
Copy after login

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.

Promise Chaining and Nested Promises

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
    })
Copy after login

This approach returns a nested promise that ultimately resolves to the desired object.

Conclusion

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template