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?
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?
Share Improve this question asked Jul 28, 2016 at 21:09 guidsenguidsen 2,4036 gold badges35 silver badges57 bronze badges 2- how are the failed differentiated from the non-failed? what do the two objects look like? – jcollum Commented Jul 28, 2016 at 21:13
- Have a look over here. Notice that it's impossible to synchronously determine the state of a promise, so the best you will get is a promise for an array of fufilled promises (or their results) – Bergi Commented Jul 28, 2016 at 21:20
1 Answer
Reset to default 11You can't inspect standard promises in a synchronous way, so you cannot filter the array by their resolution status. But you can employ Promise.allSettled
to get a list of outes. Thanks to @O-2 in the ments. Example code to get only resolved values:
const promises = [
Promise.resolve(1),
Promise.reject(2),
Promise.resolve(3)
];
const resolvedPromises = Promise.allSettled(promises).then(
values => values.filter(o => o.status === 'fulfilled').map(o => o.value)
);
resolvedPromises.then(values => console.log(values));