Node.js - 在另一个方法完全执行后调用一个方法

its*_*sme 5 javascript asynchronous node.js promise rsvp-promise

我有两个简单的方法:

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

function done(){
   return something;
}
Run Code Online (Sandbox Code Playgroud)

现在我只想确保done()do()完成时调用(**do() 方法包含对 Mysql DB 的异步请求

我怎样才能做到这一点?**

显然,这不会按顺序排列这些方法:

do(x=1,y=1);

done(); //this can run also if do() has not finished yet
Run Code Online (Sandbox Code Playgroud)

所以我尝试:

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
Run Code Online (Sandbox Code Playgroud)

这是我用于承诺的内容https://github.com/tildeio/rsvp.js/#arrays-of-promises

Ber*_*rgi 5

我知道 promises,但我不知道如何将它放入 sintax

假设XHR()确实返回了一个承诺,那么你的代码应该是这样的:

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);
Run Code Online (Sandbox Code Playgroud)