简体   繁体   English

为什么直接将Promise.all传递给.then函数会抛出错误?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM