javascript – 为什么.json()会返回一个承诺?

我最近一直在搞乱fetch()api,并注意到一些有点古怪的东西.

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => {
      return {
          data: response.json(),
          status: response.status
      }
  })
  .then(post => document.write(post.data));
;

post.data返回一个Promise对象.
http://jsbin.com/wofulo/2/edit?js,output

但是如果写成:

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => response.json())
  .then(post => document.write(post.title));
;

post这里是一个标准的Object,你可以访问title属性.
http://jsbin.com/wofulo/edit?js,output

所以我的问题是:为什么response.json在对象文字中返回一个promise,但是如果刚刚返回则返回值?

解决方法:

Why does response.json return a promise?

因为您在收到所有标题后立即收到回复.调用.json()可以获得尚未加载的http响应主体的另一个承诺.另见Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

因为that’s how promises work.从回调中返回promises并使它们被采用的能力是它们最相关的特性,它使它们可以在没有嵌套的情况下进行链接.

您可以使用

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

或等待json身体后获得响应状态的任何其他approaches to access previous promise results in a .then() chain.

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...