Home > Web Front-end > JS Tutorial > Why Does `fetch().then().json()` Sometimes Return a Promise and Sometimes Not?

Why Does `fetch().then().json()` Sometimes Return a Promise and Sometimes Not?

Mary-Kate Olsen
Release: 2024-12-11 14:19:11
Original
393 people have browsed it

Why Does `fetch().then().json()` Sometimes Return a Promise and Sometimes Not?

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:

  • Use nested .then() blocks:
fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(response.status, data.title);
  });
Copy after login
  • Use async/await (requires an async function):
const response = await fetch(url);
const data = await response.json();
console.log(response.status, data.title);
Copy after login

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!

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