Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This for have clean code.

Thanks in advance.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading