tomaj
tomaj

Reputation: 1590

Javascript Promises - get Array of non rejected

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.

Upvotes: 1

Views: 91

Answers (2)

tomaj
tomaj

Reputation: 1590

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));
}

Upvotes: 0

Bergi
Bergi

Reputation: 664559

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.

Upvotes: 2

Related Questions