7

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?

guidsen
  • 2,333
  • 6
  • 34
  • 55
  • how are the failed differentiated from the non-failed? what do the two objects look like? – jcollum Jul 28 '16 at 21:13
  • Have a look [over here](http://stackoverflow.com/a/30930421/1048572). 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 Jul 28 '16 at 21:20

1 Answers1

11

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.allSettled to get a list of outcomes. Thanks to @O-2 in the comments. 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));
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
  • 2
    In ES6, I'd even use `Symbol("failed")` instead of an empty object. – Bergi Jul 28 '16 at 21:22
  • I think `allSettled()` would be better. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled – O-9 Feb 16 '23 at 09:15
  • @O-9 you are right! In 2023, `Promise.allSettled` is a better answer, thank you! – Tamas Hegedus Feb 17 '23 at 20:00