Why does passing the Promise.all function directly to .then cause an error?

I want to pass Promise.all directly to the .then function, for example:

 const test = [ Promise.resolve(), Promise.resolve(), Promise.resolve(), Promise.resolve() ]; Promise.resolve(test) // It supposed to be an AJAX call .then(Promise.all) // Get an array of promises .then(console.log('End'); 

But this code raises an 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 does a Promise.all passed directly to .then Promise.all error? (And why does a console.log work fine?)

+5
source share
1 answer

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

From ES2015 spec :

All functions require that this value be a constructor function that supports the conventions of Promise constructor parameters.

Or it is better to use it directly in the 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)) 
+4
source

Source: https://habr.com/ru/post/1268987/


All Articles