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 ?)
throws an error, the promise returned by then gets rejected with the thrown error as its value. returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value. returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
When a value is returned from within a then handler, it will effectively return Promise.resolve (<value returned by whichever handler was called>) . A then call will return a rejected promise if the function throws an error or returns a rejected Promise. In all other cases, a resolving Promise is returned.
JavaScript | Promise.all () Method. The Promise.all () method is actually a promise that takes an array of promises (an iterable) as an input. It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved or when the iterable contains no promises. In simple way, if any of the passed-in promises ...
In other words, if any promise fails to get executed, then Promise.all () method will return an error and it will not take into the account whether other promises are successfully fulfilled or not. Example 2: Here Promise.all resolves after 2000 ms and the output is shows as an array. Here, Promise.all is the order of the maintained promises.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With