Home > Back-end >  Conditionally execute promises in Promise.all()
Conditionally execute promises in Promise.all()

Time:07-16

I have 2 promises that takes in input 2 differents parameters:

promise1(var1)
promise2(var2)

These promises runs in parallel inside a Promise.all():

Promise.all([promise1(var1), promise2(var2)])

Sometimes, depending on the value of var1 or var2, I just need one of them to be executed. For example, if var1 is null, I just want

Promise.all([promise2(var2)])

Or, if var2 is null:

Promise.all([promise1(var1)])

Is there an elegant way to code this situation without if, else branches?

CodePudding user response:

Why do you think if .. else is not elegant? In many situation it's the most readable code and thus IMHO is better than some "well-constructed" oneliner, which you won't understand anymore the next time you are reading it.

I personally would make an array and push the various promises into that array based on the conditions. And then finally make a Promise.all with this array. IMO this is the most readable and elegant way to do this.

let promises = [];  
if (val1) promises.push(promise1(val1));
if (val2) promises.push(promise1(val2));
Promise.all(promises);

CodePudding user response:

Promise.all([
var1 ? promise1(var1) : Promise.resolve(null),
var2 ? promise2(var2) : Promise.resolve(null),
]);

CodePudding user response:

it can be done with dynamically create promise.all array argument.

var promises=[];
if(var1==null)
promise.push(promise2(var2));

if(var2==null)
promise.push(promise1(var1));

Promise.all(promises);

CodePudding user response:

I would not go for a solution where sometimes you pass an array with 2 promises to Promise.all, and sometimes just 1. If ever you need to get the resolved values from what Promise.all returns, you'll just have a harder time to determine where a value came from. So don't play with the array size. Keep it predetermined.

The better solution would be to adapt the promise1 and promise2 function so that they return null or undefined when the argument they get is null (or whatever you want to treat differently). Then call Promise.all as you did in your initial code:

Promise.all([promise1(var1), promise2(var2)])

If you don't want to touch the functions promise1 and promise2, then do:

Promise.all([(var1 !== null) && promise1(var1),
             (var2 !== null) && promise1(var2)]);

Note that there is no issue when you have a non-promise value in that array. This will be treated as an immediately resolved promise.

  • Related