Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter rejected Promises

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?

like image 351
guidsen Avatar asked Jul 28 '16 21:07

guidsen


People also ask

What happens if Promise is rejected?

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.

Does Promise allSettled () reject?

allSettled() method will not reject itself if any of the passed in promise input inside an array is rejected.

How do you use filters in Promise?

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.

What promises reject returns?

reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error .


1 Answers

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));
like image 69
Tamas Hegedus Avatar answered Oct 13 '22 15:10

Tamas Hegedus