为什么.json()会返回一个承诺? [英] Why does .json() return a promise?

查看:167
本文介绍了为什么.json()会返回一个承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been messing around with the fetch() api recently, and noticed something which was a bit quirky.

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

post.data returns a promise object. 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));
;

这里发布的是一个标准对象,您可以访问title属性。
http://jsbin.com/wofulo/edit?js,output

post here is a standard object which you can access the title attribute. http://jsbin.com/wofulo/edit?js,output

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

So my question is: why does response.json return a promise in an object literal, but return the value if just returned?

推荐答案


为什么 response.json 返回一个承诺?

因为当所有标题到达时您收到响应。调用 .json()可以获得尚未加载的http响应正文的承诺。另请参见为什么来自JavaScript fetch API的响应对象是一个承诺?

Because you receive the response when all headers have arrived. Calling .json() gets you a promise for the body of the http response that is yet to be loaded. See also 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?

因为承诺如何运作。从回调中返回承诺并获得它们的能力是它们最相关的功能,它使它们可以在没有嵌套的情况下进行链接。

Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.

你可以使用

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

或任何其他访问先前的promise的方法导致.then()链在等待json主体后获得响应状态。

or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.

这篇关于为什么.json()会返回一个承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆