我能以某种方式在第一个“then”中获得获取响应吗?

Can I somehow get the fetch response in the first `then`?

我正在尝试使用 Fetch API。从示例来看,GET 请求似乎需要 then 以某种方式解析响应。

目前我正在做这个

fetch(url)
    .then(response => response.json())
    .then(response => {
        console.log(response);  
    });

然而,第一个 then 看起来像是样板。我尽量避免了,例如:

fetch(url)
    .then(response => {
        console.log(response.json());  
    });

但是这记录了一个状态为 resolved.

的未决 Promise

我阅读了有关此主题的其他问题并阅读了一些有关承诺的内容,但我无法理解是否可以将其组合成一个 then(如果可以 - 如何?)。

例如,其中两个答案指出

There is no need to use more than one '.then'

there is no good reason to have two .then() handlers as the code from each could have been combined into a single .then() handler

但我无法让该示例实际工作 - 我仍然得到了承诺:)

相反,公认的答案 解释说 .then 实际上对结果做了一些事情(从 promise 中提取返回值),但如果我能以某种方式做到这一点,我无法理解我自己,说 response.json().then()response.json().getVal() 或者双 then 语法是唯一的方法。

非常简单:当您发送 fetch() 请求时,它 return 是一个包含响应的承诺。这是由第一个 .then() 解决的。解决这个第一个承诺实际上 returns Response.

现在这是棘手的部分:读取响应正文的方法,可以是 .json().text().blob()... 所有 return 承诺。这意味着您需要解决第二个承诺才能获得解析后的响应。

流程如下所示:

  1. 发出一个 fetch() 请求,它 return 是一个 Response
  2. 类型的 Promise
  3. 当您尝试解析 Response 的内容时,它将 return 第二个 Promise,其类型取决于您使用的方法(例如 .json() returns 一个对象, .text() returns 字符串, .blob() returns Blob).
  4. 解决第二个 Promise,您将获得实际解析的响应主体

p/s:如果您没有在顶级上下文中使用 fetch()(在编写顶级 await 时仍然不是问题),那么您可以使用async/await 让您的代码更具可读性:

const response = await fetch(url);
const content = await response.json();
console.log(content);

fetch 返回的第一个承诺在某些情况下很有用。如果你想避免样板,你可以简单地创建你自己的函数:

function fetch_json(url, opts) {
    return fetch(url, opts)
        .then(resp => resp.json());
}

fetch_json(your_url)
    .then(json => console.log(json));

这些天我使用的是 async/await 语法,它是一回事,但对我来说看起来不像样板文件。

const response = await fetch(url)
const data = await response.json()

console.log(data)