Node.js - method call after another method is executed

I have 2 simple methods:

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

function done(){
   return something;
}

now I just want to call done()when do()finished (** do () method contains asynchronous queries in Mysql DB )

how can i achieve this **

Obviously, such methods will not be executed sequentially:

do(x=1,y=1);

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

So I tried:

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

+4
source share
3 answers

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

Assuming it XHR()returns a promise, here is what your code looks like:

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

node.js , . , 2 .

  • Callbacks. . . "callback hell" node. 2, , , .

  • promises. , promises. , promises Promise . - , . , , . : promises node.js

+4

:

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

. fs.readFile();

- , , - :

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 asynchronous calls you made, and calls _callbackwhen everything is done. But you need to add a callback to the methods XHR().success().

+1
source

Source: https://habr.com/ru/post/1527937/


All Articles