我最近一直在搞乱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));
;
Run Code Online (Sandbox Code Playgroud)
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));
;
Run Code Online (Sandbox Code Playgroud)
post这里是一个标准对象,您可以访问title属性. http://jsbin.com/wofulo/edit?js,output
所以我的问题是:为什么response.json在对象文字中返回一个promise,但是如果刚刚返回则返回值?
我从 JS 开始,实际上喜欢异步方面(来自 Python),但我不确定为什么有些函数会返回 Promise。具体来说,下面的代码 usingfetch
让我想知道返回的是什么json()
:
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
return response.json()
})
.then((json) => {
Object.keys(json).forEach((key) => {
console.log("got " + key)
})
})
Run Code Online (Sandbox Code Playgroud)
撇开流不谈,我们在 a 之后得到的 HTTP 响应GET
是一个文本块,稍后由客户端解释以提取标头、正文和其他有趣的元素 - 作为 HTTP 内容分析的一部分。
关键是这个文本块是一个整体,所以第一个then()
已经有了整个响应——为什么解析 JSON 正文是一个异步操作,forEach
与第二个不同then()
?
换句话说,为什么我不能让以下代码工作?
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
Object.keys(response.json()).forEach((key) => {
console.log("got " + key)
})
})
Run Code Online (Sandbox Code Playgroud)
注意:如果第一个代码运行不正确(带有ERR_BLOCKED_BY_CLIENT
),请尝试禁用您的广告拦截器。第二个是故意不正确的。
当客户端提取请求导致服务器端出错时,我想返回错误代码(400)和自定义消息.我不知道如何使用fetch和promises优雅地在客户端检索这两者.
return fetch('/api/something')
.then(response => response.json())
.then(json => {
console.log(json.message)
// I only have access to the json here.
// I'd also like to get the response status code
// (from the response object) and potentially
// throw an error complete with the custom message.
})
.catch(function(ex) {
console.log('Unhandled Error! ', ex);
});
Run Code Online (Sandbox Code Playgroud)
谢谢!
fetch-api ×2
javascript ×2
promise ×2
asynchronous ×1
ecmascript-6 ×1
es6-promise ×1
fetch ×1
json ×1