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 ?)
1 Answer
Reset to default 10You 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))