我最近一直在搞乱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,但是如果刚刚返回则返回值?
我在前端和后端(NodeJS)都使用了Fetch API,在将响应解析为json时,我遇到了很多问题.
response.json() 将返回一个promise,所以我事先不知道响应的主体是什么,当body是空的时,JSON解析将失败,并显示错误:
SyntaxError: Unexpected end of input
所以我的问题是,如何在空的情况下防止解析响应?
谢谢