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

187
Visualizações
Better way to call conditionally promises

I have a scenario where I have "Promise A" and "Promise B". I need to call both promises only if the variable "value" is false, else, I only need to call the Promise B.

So, I wrote this code:

if(!value){
            PromiseA.then((newValue)=>{
                PromiseB.then((newValue)=>{
                    //...
                })
            })
        }
        else{
            PromiseB.then((value)=>{
                //....
            })
        }

This code works fine, but I'm wondering if there is a better way to accomplish this than using "if-else".

This for have clean code.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Inside an async function, await the first Promise if you need to.

const firstValue = value ?? await PromiseA;
const resultOfPromiseB = await PromiseB;
// do stuff with resultOfPromiseB
about 4 years ago · Juan Pablo Isaza Relatório

0

You can wrap the second promise in a function if you want to avoid code repetition.

function callPromiseB() {
   PromiseB.then((value)=>{
      //....
   })
}

        if(!value){
            PromiseA.then((newValue)=>{
                callPromiseB()
            })
        }
        else{
            callPromiseB()
        }
about 4 years ago · Juan Pablo Isaza 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