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
正常工作?)
为什么? (我不能直接在数组上使用它,这个数组来自Ajax调用,我会更新我的问题) – RChanaud
@RChanaud [Spec](https://tc39.github.io/ecma262/2017/#sec- promise.all)这样说:“让C为这个值。 如果Type(C)不是Object,则抛出一个TypeError异常。” “ all函数要求它的这个值是一个构造函数,它支持Promise构造函数的参数约定。” –
@RChanaud我怀疑你的ajax请求神奇地返回promise。因此,仍然有一个地方可以在'then'回调中创建一个promise数组,以便您可以返回'Promise.all(promise)'而不是数组 –