David Tzoor David Tzoor - 3 months ago 9
Javascript Question

javascript - run promises in parallel but handle rejections separately

I use

bluebird.js
map
function to perform parallel requests to an external API I use.

whenever any of the inner promises gets rejected, the
map
function also gets rejected (I know that this is by design).

I was wondering if there is any way to run promises in parallel but handle each rejection separately, and not fail the entire Promise.

Answer

I would use .reflect with the map to get promise inspections as the result:

const all = Promise.map(items, item => doSomething(item).reflect());

all.then(items => {
  // will contain an array of the promises that fulfilled correctly
  let fulfilled = items.filter(x => x.isFulfilled()).map(x => x.value()));
  // will contain an array of the promises that rejected 
  // so you can handle the errors
  let rejected = items.filter(x => x.isRejected()).map(x => x.reason());

});
Comments