Home > Enterprise >  Better way to call conditionally promises
Better way to call conditionally promises

Time:03-17

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.

CodePudding user response:

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

CodePudding user response:

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()
        }
  • Related