2017-06-13 157 views
2

我一直在嘗試獲得一組承諾來同時解決所有問題。我知道Promise.prototype.then()接受它接受解析值的回調:承諾鏈中的Promise.all與x => Promise.all(x)有什麼區別?

const one = Promise.resolve(1) 
 

 
one.then(console.log) // 1 
 
one.then(x => console.log(x)) // 1

當我嘗試調用Promise.all承諾的陣列上,我不得不使用一個回調使其工作。

const two = Promise.resolve(2) 
 
const three = Promise.resolve(3) 
 

 
Promise.resolve([two, three]) 
 
    .then(xs => Promise.all(xs)) // Works 
 
    .then(console.log) // [2,3] 
 
    
 
Promise.resolve([two,three]) 
 
    .then(Promise.all) // Error 
 
    .then(console.log)

這是怎麼回事嗎?爲什麼我不能傳遞Promise.all並讓它作爲回調函數工作?爲什麼我必須「手動」調用它?

回答

3

Promise.all預計將被調用Promise *作爲this對象。這會工作(但比箭頭功能更詳細):

Promise.resolve([two, three]) 
    .then(Promise.all.bind(Promise)) 
    .then(console.log) 

*從技術上講,這是指定here;它可以通過多種方式在另一個類似於Promise的構造函數上調用,但實際上您會想要使用Promise本身。

相關問題