2016-12-01 43 views
3

我有測試代碼!承諾,獲取,codestyle。請解釋。然後(checkStatus)。然後(parseJSON)

function checkStatus(response) { 
    if (response.status >= 200 && response.status < 300) { 
     return Promise.resolve(response) 
    } else { 
     return Promise.reject(new Error(response.statusText)); 
    } 
} 
function parseJSON(response) { 
    return response.json() 
} 

我可以寫喜歡這裏:

function load(id) { 
    return fetch('/api/test/'+ id + '/', {method: 'get'}) 
       .then(response => checkStatus(response)) 
       .then(response => parseJSON(response)) 
       .catch(error=>console.error(error)) 

或者我可以這樣寫有:

function load(id) { 
    return fetch('/api/test/'+ id + '/', {method: 'get'}) 
       .then(checkStatus) 
       .then(parseJSON) 
       .catch(error=>console.error(error)) 

請解釋第二個變體。 .then(checkStatus) .then(parseJSON)如何工作?
我只寫了函數的引用,並沒有運行它。

回答

3

.then需要的功能作爲參數......它調用傳遞是承諾的決心值的單個參數的函數

這麼認爲的

return fetch('/api/test/'+ id + '/', {method: 'get'}) 
.then(checkStatus) 

return fetch('/api/test/'+ id + '/', {method: 'get'}) 
.then(function(resultOfPromise) { 
    return checkStatus(resultPromise); 
}) 

順便說一句,這不僅限於承諾/然後鍵入代碼...考慮以下內容

function doThings(p1) { 
    console.log(p1); 
    return 'good bye'; 
} 
setTimeout(doThings, 1000, "hello world"); 

同樣的概念 - 除了在setTimout回調的返回值被忽略。然而,在.then(),回調返回的值用作Promise的解析值......基本上,promise鏈是如何工作的(這是一個簡單的解釋)

+0

@oksana但是,有微妙的差異在這個'''this'''指向的兩個變體之間將指向你傳遞給'''然後''' – balajisoundar

+1

@balajisoundar函數的內部 - 這就是爲什麼我使用了* think * * A'* as * 'B'。而不是說'A' *就像*'B' –

+0

只是指出了差異。 – balajisoundar