2017-06-19 65 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)'而不是数组 –

相关问题