Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Conditionally execute promises in Promise.all()

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?

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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);
about 4 years ago · Santiago Gelvez Report

0

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);
about 4 years ago · Santiago Gelvez Report

0

Promise.all([
var1 ? promise1(var1) : Promise.resolve(null),
var2 ? promise2(var2) : Promise.resolve(null),
]);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!