Is it possible to break away from await Promise.all when any promise has fulfilled (Chrome 80) Is it possible to break away from await Promise.all when any promise has fulfilled (Chrome 80) google-chrome google-chrome

Is it possible to break away from await Promise.all when any promise has fulfilled (Chrome 80)


In this case Promise.race() looks reasonable but the problem with Promise.race() is any rejecting promise in the race will collapse the whole race. If what we want is to ignore the individual rejections and carry on with the race then we still have an option in which case only if all promises gets rejected we have to perform an action to handle the error.

So if we invent the Promise.invert() and use it with Promise.all() then we get what we want.

var invert = pr => pr.then(v => Promise.reject(v), x => Promise.resolve(x));

Lets see how we can use it;

var invert     = pr  => pr.then(v => Promise.reject(v), x => Promise.resolve(x)),    random     = r   => ~~(Math.random()*r),    rndPromise = msg => random(10) < 3 ? Promise.reject("Problem..!!!")                                       : new Promise((v,x) => setTimeout(v,random(1000),msg)),    promises   = Array.from({length: 4}, (_,i) => rndPromise(`Promise # ${i}.. The winner.`));Promise.all(promises.map(pr => invert(pr)))       .then(e => console.log(`Error ${e} happened..!!`))       .catch(v => console.log(`First successfully resolving promise is: ${v}`));

So since the promises are inverted now catch is the place that we handle the result while then is the place for eror handling.

I think you can safely use this in production code provided you well comment this code block for anybody reading in future.