为什么 .json() 返回一个承诺? [英] Why does .json() return a promise?
问题描述
我最近一直在使用 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
但是如果写成:
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
post
here is a standard Object
which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output
所以我的问题是:为什么 response.json
在对象字面量中返回一个承诺,但如果刚刚返回则返回值?
So my question is: why does response.json
return a promise in an object literal, but return the value if just returned?
推荐答案
为什么
response.json
会返回一个 promise?
Why does
response.json
return a promise?
因为您会在所有标头到达后立即收到 response
.调用 .json()
可以为您提供尚未加载的 http 响应正文的另一个承诺.另请参阅为什么来自 JavaScript fetch API 的响应对象是承诺?.
Because you receive the response
as soon as all headers have arrived. Calling .json()
gets you another 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?.
如果我从 then
处理程序返回承诺,为什么我会得到值?
Why do I get the value if I return the promise from the
then
handler?
因为这就是承诺的工作方式.从回调中返回 promise 并让它们被采用的能力是它们最相关的特性,它使它们无需嵌套即可链接.
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)
}));
或任何其他访问先前承诺的方法会导致 .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屋!