比如
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
一般我们想要的数据在第二层then里面,那第一层then的respose有什么用,为什么还要return?里面是什么信息?状态码?
比如
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
一般我们想要的数据在第二层then里面,那第一层then的respose有什么用,为什么还要return?里面是什么信息?状态码?
感谢 @liqi0816 提醒,对fetch apis不是太属性,楼上的答案已经很明了了,以下是以前不了解fetch时候的回答。
泻药。看起来fetch是Promise方法。
先说理解,Promise通过then构建的时候,是把then接收的回调方法,一层层的构建回调串。下一个then里的回调方法的参数是上一个then里回调方法的返回结果。比如你第二个then回调方法的data
参数就是上一个then回调最后return的response.json()
,如果你不return,那么第二个then回调无法接收到参数传递。
再回到你的问题,除非你有独立的处理data的函数或方法,否则直接这样写就行
fetch(url).then(function(response) {
let data = response.json();
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
MDN说的已经很清楚了,response.json()返回一个promise对象,所以需要把这个promise对象返回,然后在下一个then回调里获取到真正的返回数据。
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
response是Response对象,包含Header、status、statusText等属性。要获得具体数据需要使用
.json
(用于JSON)、.text
(用于文本)、.formData
(用于FormData对象)等方法。至于为什么需要
return
,因为Response.json
返回的是一个Promise,所以只能先return,再在下一层处理。