我最近一直在弄乱 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?
因为您会在所有 header 到达后立即收到响应
。调用 .json()
为尚未加载的 http 响应正文提供另一个 promise 。另见 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 .从回调中返回 promise 并让它们被采用的能力是它们最相关的特性,它使它们无需嵌套即可链接。
你可以使用
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
或任何其他 approaches to access previous promise results in a .then() chain在等待 json 正文后获取响应状态。
关于javascript - 为什么 .json() 返回一个 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555031/