鍍金池/ 問答/Linux  HTML/ fetch第一層回調(diào)的結(jié)果response是什么,為什么返回的數(shù)據(jù)是在第二層th

fetch第一層回調(diào)的結(jié)果response是什么,為什么返回的數(shù)據(jù)是在第二層then里面

比如

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

一般我們想要的數(shù)據(jù)在第二層then里面,那第一層then的respose有什么用,為什么還要return?里面是什么信息?狀態(tài)碼?

回答
編輯回答
任她鬧

response是Response對象,包含Header、status、statusText等屬性。要獲得具體數(shù)據(jù)需要使用.json(用于JSON)、.text(用于文本)、.formData(用于FormData對象)等方法。
至于為什么需要return,因為Response.json返回的是一個Promise,所以只能先return,再在下一層處理。


fetch(url).
    then(function(response) {
        // 打印響應(yīng)頭
        console.log(response.headers);
        //打印狀態(tài)碼
        console.log(response.status);
        //打印狀態(tài)信息
        console.log(response.statusText);
        // 使用.json方法獲得具體返回數(shù)據(jù),再下一層Promise里處理
        return response.json();
    })
    .then(function(data) { console.log(data); })
    .catch(function(e) { console.log("Oops, eror");
2018年4月4日 04:56
編輯回答
挽歌

感謝 @liqi0816 提醒,對fetch apis不是太屬性,樓上的答案已經(jīng)很明了了,以下是以前不了解fetch時候的回答。


瀉藥??雌饋韋etch是Promise方法。
先說理解,Promise通過then構(gòu)建的時候,是把then接收的回調(diào)方法,一層層的構(gòu)建回調(diào)串。下一個then里的回調(diào)方法的參數(shù)是上一個then里回調(diào)方法的返回結(jié)果。比如你第二個then回調(diào)方法的data參數(shù)就是上一個then回調(diào)最后return的response.json(),如果你不return,那么第二個then回調(diào)無法接收到參數(shù)傳遞。
再回到你的問題,除非你有獨立的處理data的函數(shù)或方法,否則直接這樣寫就行

fetch(url).then(function(response) {
  let data = response.json();
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});
2017年4月22日 08:42