達令說
2019-03-20 22:15:16
比如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?里面是什么信息?狀態碼?
2 回答

溫溫醬
TA貢獻1752條經驗 獲得超4個贊
response是Response對象,包含Header、status、statusText等屬性。要獲得具體數據需要使用.json
(用于JSON)、.text
(用于文本)、.formData
(用于FormData對象)等方法。
至于為什么需要return
,因為Response.json
返回的是一個Promise,所以只能先return,再在下一層處理。
fetch(url).
then(function(response) {
// 打印響應頭
console.log(response.headers);
//打印狀態碼
console.log(response.status);
//打印狀態信息
console.log(response.statusText);
// 使用.json方法獲得具體返回數據,再下一層Promise里處理
return response.json();
})
.then(function(data) { console.log(data); })
.catch(function(e) { console.log("Oops, eror");
添加回答
舉報
0/150
提交
取消