1

I need a function that can take an Array<Promise<Object>> and return an Promise<Array<Object>>.

It would be similar to a Promise.all(), but instead of failing on a reject it just ignores them, and moves on.

tomaj
  • 1,570
  • 1
  • 18
  • 32

2 Answers2

2

You can use Promise.all to transform an Array<Promise<X>> to a Promise<Array<X>>.

To ignore rejections, just handle them and return some null value instead:

Promise.all(promises.map(p => p.catch(err => undefined)))

If you are interested in completely filtering them out, use this approach that post-processes the array.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

We went with the solution described by @Bergi, you can see it here.

Slightly simplified example follows:

function preloadImages(imagePromises) {
  const IMAGE_LOAD_FAIL = null;

  const promises = imagePromises
    .map(image => image.catch(err => IMAGE_LOAD_FAIL));

  return Promise.all(promises)
    .then(images =>  images.filter(image => image !== IMAGE_LOAD_FAIL));
}
tomaj
  • 1,570
  • 1
  • 18
  • 32