Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding callback hell in promises using nodejs

I have written about a half a dozen functions in nodejs using promises, i want really post all of that code, instead i will post a simulated example , so i can encapsulate my problem succinctly. so say i have 2 functions below:

foo = () => {
    return new Promise( ( r , rj ) => {
       setTimeout( () => {
             r('DONE');
       }, 3000 );
    }); 
}  

And

bar = () => {
    return new Promise( (r , rj) => { r('ALL DONE !') } )
}

Now i would like to avoid the callback hell and do the following:

foo().then( (resp) => console.log(resp) ).bar()

Instead what i am forced to do is this:

foo().then( (resp) => { console.log(resp); bar() } )

So basically in my production code i have something like the below, so far(just to give you an idea):

let uploadToVault = ( INPUT_DIR , VOLT_CRED ) => {

    INPUT_DIRECTORY = INPUT_DIR;
    VOLT_CREDENTIALS = VOLT_CRED;

    volt_APILogin().then( () => {
        volt_getProduct().then( () => {
           volt_CreatePresentation().then( (resp) => {
                console.log(resp);        
                volt_uploadSlides().then( (resp) => {
                    console.log(resp);
                    volt_bindSlide().then( (resp) => {
                        console.log(resp);
                    });
                });
           });  
        });
    });
}

Now how can i write this in more a chain format vs writing this in a callback ?

like image 364
Alexander Solonik Avatar asked Dec 18 '25 07:12

Alexander Solonik


1 Answers

The idea would be to always return a promise:

volt_APILogin()

    .then(() => {
        return volt_getProduct();
    })
    .then(() => {
         return volt_CreatePresentation();
    })
    .then((resp) => {
         console.log(resp);        
         return volt_uploadSlides();
    })
    .then((resp) => {
         console.log(resp);
         return volt_bindSlide();
    })
    .then((resp) => {
         console.log(resp);
         return Promise.resolve('just for fun');
    })
    .then((resp) => {
         console.log("This round is", resp);
    });

Then, if there are intermediary values you need to use down the chain, just collect them to variables outside the chain.

like image 192
Sami Hult Avatar answered Dec 19 '25 22:12

Sami Hult



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!