Why passing directly Promise.all to a .then function throws an error?

时间:2017-06-19 14:03:45

标签: javascript

I want to pass directly Promise.all to a .then function like:

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.

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 ? (And why a console.log works fine ?)

1 个答案:

答案 0 :(得分:6)

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

来自ES2015 spec

  

all函数要求它的this值是一个构造函数,它支持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))