Is It Possible To Break Away From Await Promise.all When Any Promise Has Fulfilled (chrome 80)
I need to send a request to multi-servers to see which server will response to my request and if any of them response, I will then further interact with this server. The simplest w
Solution 1:
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.
varinvert = pr => pr.then(v =>Promise.reject(v), x =>Promise.resolve(x));
Lets see how we can use it;
varinvert = pr => pr.then(v =>Promise.reject(v), x =>Promise.resolve(x)),
random = r => ~~(Math.random()*r),
rndPromise = msg =>random(10) < 3 ? Promise.reject("Problem..!!!")
: newPromise((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.
Post a Comment for "Is It Possible To Break Away From Await Promise.all When Any Promise Has Fulfilled (chrome 80)"