Node.js - call a method after another method is fully executed

itsme picture itsme · Feb 20, 2014 · Viewed 26.7k times · Source

I have 2 simple methods:

 function do(x,y){
   if(x){
    XHR1().success();
   }
   if(y){
    XHR2().success();
   }
}

function done(){
   return something;
}

now i just would like to be sure to call done() when do() has finished (**do() method contains async requests to Mysql DB)

how can i achieve this?**

Obviously this won't put such methods in sequence:

do(x=1,y=1);

done(); //this can run also if do() has not finished yet

So i tryed:

function do(x,y,_callback){
       if(x){
        XHR1().success();
       }
       if(y){
        XHR2().success();
       }

      _callback();
    }

    function done(){
       return something;
    }

do(x=1,y=1,done()); // this won't work the same cause callback is not dependent by XHR response

this is what i use for promises https://github.com/tildeio/rsvp.js/#arrays-of-promises

Answer

Bergi picture Bergi · Feb 20, 2014

i know about promises but i can't get how to put it in sintax

Assuming that XHR() does return a promise, this is what your code should look like then:

function do(x,y) {
    var requests = [];
    if (x)
        requests.push( XHR1() );
    if (y)
        requests.push( XHR2() );
    return RSVP.all(requests);
}
function done(){
    return something;
}

do(1, 1).then(done);