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

3

5

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

Cheiro answered 20/2, 2014 at 15:47 Comment(3)
Use a callback or a promise.Blowpipe
@Matt Ball a promise is ok but i can't get how to resolve it if i have more then 1 async call in do()Cheiro
you have to place each callback inside the previous. Anything outside a callback is going to be executed immediately.Ide
M
5

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);
Manners answered 20/2, 2014 at 16:41 Comment(1)
thanks man i need this, i'm using RSVP.js github.com/tildeio/rsvp.js/#arrays-of-promisesCheiro
T
4

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

Turmel answered 20/2, 2014 at 16:7 Comment(1)
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 meCheiro
C
1

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.

Centra answered 20/2, 2014 at 15:59 Comment(3)
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 1Cheiro
not quite sure if you catched the problem i updated the question with cleaner code, thanksCheiro
@Centra The asyncFunc2 is not defined, and link is not working. Can you elaborate with real example?Iwo

© 2022 - 2024 — McMap. All rights reserved.