Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

Promise.all([
var1 ? promise1(var1) : Promise.resolve(null),
var2 ? promise2(var2) : Promise.resolve(null),
]);
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda