[英]Why passing directly Promise.all to a .then function throws an error?
I want to pass directly Promise.all
to a .then
function like: 我想直接传递
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');
But this code throws an error Uncaught (in promise) TypeError: Promise.all called on non-object
. 但是这段代码抛出了一个错误
Uncaught (in promise) TypeError: Promise.all called on non-object
。
When I remove the shorthand syntax, it works: 当我删除速记语法时,它的工作原理如下:
Promise.resolve(test)
.then(queries => Promise.all(queries))
.then(console.log('End'));
So why a Promise.all
passed directly to a .then
throws an error ? 那么,为什么一个
Promise.all
直接传递到.then
抛出一个错误? (And why a console.log
works fine ?) (为什么
console.log
工作正常?)
You need to bind Promise.all.bind(Promise)
你需要绑定
Promise.all.bind(Promise)
From ES2015 spec : 从ES2015 规范 :
The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.
all函数要求其this值为构造函数,该函数支持Promise构造函数的参数约定。
Or better use it directly on array. 或者更好地直接在阵列上使用它。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.