I have an array of Promise
objects where I want to map on and filter the rejected Promises.
Expected output:
const promises = [
failedPromise,
successPromise,
successPromise,
];
const resolvedPromises = promises.map(promise => ???);
The resolvedPromises
variable should container the output of the two successPromise
promises.
How would I implement such algorithm?
This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.
allSettled() method will not reject itself if any of the passed in promise input inside an array is rejected.
Bookmark this question. Show activity on this post. let arr = [1,2,3]; function filter(num) { return new Promise((res, rej) => { setTimeout(() => { if( num === 3 ) { res(num); } else { rej(); } }, 1); }); } function filterNums() { return Promise.
reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error .
You can't inspect standard promises in a synchronous way, so you cannot filter the array by their resolution status. But you can employ Promise.all
to get a list of the resolved values. Here is a little trick how to handle rejections:
const promises = [
Promise.resolve(1),
Promise.reject(2),
Promise.resolve(3)
];
const FAIL_TOKEN = {};
const resolvedPromises = Promise.all(
promises.map(p => p.catch(e => FAIL_TOKEN))
).then(
values => values.filter(v => v !== FAIL_TOKEN)
);
resolvedPromises.then(values => console.log(values));
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