我最近一直在搞乱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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。