Clean way to wait for first true returned by Promise

  • A+
Category:Languages

I'm currently working on something where I fire out three promises in an array. At the moment it looks something like this

var a = await Promise.all([Promise1(), Promise2(), Promise3()]); 

Now all of those promises will either return true or false. But at the moment I'm waiting for all of them to be finished and I could go on as soon as one of them returns true.

I thought of ways to accomplish that but all seem kind of ugly. How would you guys solve this task?

 


You can create a new promise that resolves as soon as any given promise resolves to true like this:

function promiseRaceTrue(promises) {     return new Promise(function(resolve, reject) {         promises.forEach(promise =>             promise.then(val => val === true && resolve())             // TODO handle resolve with value of "false"?             // TODO handle rejection?         );         // TODO handle all resolved as "false"?     }); }  var a = await promiseRaceTrue([Promise1(), Promise2(), Promise3()]); 

It behaves similar to Promise.race but only resolves if one of the given promises resolves with the value true instead of resolving as soon as any of the given promises either resolves or rejects.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: