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

26,646

Solution 1

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);

Solution 2

As node.js is asynchronous by nature, normal imperative flow of control doesn't work any more. You have several options, of which 2 are the most widely used.

  1. Callbacks. You can pass the second method as an argument to the first. Then in the first, execute the passed callback once the task is done. The disadvantage of this approach is usually referred to as "callback hell" in the node community. If the methods are not 2, but more, then you have to pass and nest callbacks more and more, creating a huge nested structure.

  2. Use promises. There are many libraries that implement the promises pattern. In short, promises allow you to return a Promise object from each method. A promise is an object, which will finish its work in the future. It lets you call methods on it, letting it know what needs to happen once it finishes. Take a look at this article for more info: Understanding promises in node.js

Solution 3

A popular pattern for async methods are.

asyncFunc1(arguments, function(err, data){
    if(err) throw err;

    // Do your stuff
});


function asyncFunc1(arguments, callback) {
    asyncFunc2(arg, function(err, data) {
        if(err) return callback(err);

        // Do your stuff

        callback(null, result);
    });
}

See for an example fs.readFile();

Edit

Still using callbacks but not that particular pattern you could use something like this:

function do(x,y,_callback){
  var count = 0;

  if(x){
    count++;
    XHR1().success(checkDone);
  }
  if(y){
    count++;
    XHR2().success(checkDone);
  }

  function checkDone(){
    count--;
    if(!count) _callback();
  }
}

function done(){
   return something;
}

do(x=1,y=1,done());

The counter keeps track of how many async calls you have made and calls the _callback when all are done. But you need to add a callback to the XHR().success() methods.

Share:
26,646
itsme
Author by

itsme

JS

Updated on April 21, 2020

Comments

  • itsme
    itsme about 4 years

    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

  • itsme
    itsme about 10 years
    yes but what if you have function 1(){ if(x= 0){ async1() } if(y=0){ async2()} } ?? they must be separated i can't include async2 in async 1
  • itsme
    itsme about 10 years
    please check question is updated cleaner code, i know about promises and callbacks are solutions but i can't get how to put it in sintax , please help me
  • itsme
    itsme about 10 years
    not quite sure if you catched the problem i updated the question with cleaner code, thanks
  • itsme
    itsme about 10 years
    thanks man i need this, i'm using RSVP.js github.com/tildeio/rsvp.js/#arrays-of-promises
  • Manohar Reddy Poreddy
    Manohar Reddy Poreddy over 6 years
    @pstenstrm The asyncFunc2 is not defined, and link is not working. Can you elaborate with real example?