2017-06-19 28 views
5

我想直接Promise.all傳遞給.then功能,如:爲什麼直接將Promise.all傳遞給.then函數會引發錯誤?

const test = [ 
    Promise.resolve(), 
    Promise.resolve(), 
    Promise.resolve(), 
    Promise.resolve() 
]; 

Promise.resolve(test) // It's supposed to be an AJAX call 
.then(Promise.all) // Get an array of promises 
.then(console.log('End'); 

但這代碼拋出錯誤Uncaught (in promise) TypeError: Promise.all called on non-object

當我刪除了語法速記,它的工作原理:

Promise.resolve(test) 
.then(queries => Promise.all(queries)) 
.then(console.log('End')); 

那麼,爲什麼直接傳遞到.then一個Promise.all拋出一個錯誤? (爲什麼一個console.log正常工作?)

回答

4

您需要綁定Promise.all.bind(Promise)

從ES2015 spec

的所有功能要求其此值是支持的參數約定一個構造函數Promise構造函數。

或者直接在陣列上直接使用它。

const test = [ 
 
    Promise.resolve(1), 
 
    Promise.resolve(2), 
 
    Promise.resolve(3), 
 
    Promise.resolve(4) 
 
] 
 

 
Promise.resolve(test) 
 
    .then(Promise.all.bind(Promise)) 
 
    .then(x => console.log(x)) 
 
    
 
Promise.all(test) 
 
    .then(x => console.log(x))

+0

爲什麼? (我不能直接在數組上使用它,這個數組來自Ajax調用,我會更新我的問題) – RChanaud

+0

@RChanaud [Spec](https://tc39.github.io/ecma262/2017/#sec- promise.all)這樣說:「讓C爲這個值。 如果Type(C)不是Object,則拋出一個TypeError異常。」 「 all函數要求它的這個值是一個構造函數,它支持Promise構造函數的參數約定。」 –

+2

@RChanaud我懷疑你的ajax請求神奇地返回promise。因此,仍然有一個地方可以在'then'回調中創建一個promise數組,以便您可以返回'Promise.all(promise)'而不是數組 –

相關問題