最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why passing directly Promise.all to a .then function throws an error? - Stack Overflow

programmeradmin0浏览0评论

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 ?)

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 ?)

Share Improve this question edited Jun 19, 2017 at 14:13 RChanaud asked Jun 19, 2017 at 14:03 RChanaudRChanaud 1942 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You need to bind Promise.all.bind(Promise)

From ES2015 spec:

The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

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))

发布评论

评论列表(0)

  1. 暂无评论