如何让一个函数调用等到另一个函数调用完成

How to get a function call to wait till another one is finished

所以我想要的是,

functionA(); // this completes 
functionB(); // then this runs

我试图一次性将多个集合播种到数据库中,当我按程序将每个集合依次放置时,只有最后一个集合被播种到数据库中。我正在尝试弄清楚如何避免 Javascript 成为异步的,这样我就可以让每一步都等到前一步完成。我觉得我可以使用 Underscores "defer" 方法,该方法会延迟调用该函数,直到当前调用堆栈已清除;我只是不知道如何使用它。

我正在使用下划线延迟方法,这很有效,但它取决于种子大小,我想摆脱它。

代码如下所示:

// creates and sends seed data to a collecion("blah") inside a db("heroes")
var blog = MeanSeed.init("heroes", "blah");
blog.exportToDB();

// this waits a second till it starts seeding the "heroes" DB with its "aliens" collection
_.delay(function() {
  var user = MeanSeed.init("heroes", "aliens");   
  user.exportToDB();  
}, 1000)

您可以使用回调函数,如下所示:

function functionA(done){
    //do some stuff
    done(true);
}
function functionB(){

}

functionA(function(success){
    if(success)
        functionB();
});

或者,您可以使用承诺。

我可以推荐使用 Promises。它非常新,它是在 ES6 中引入的(但它已经在 Node 5-6 中)。使用示例:

new Promise(function(resolve, reject){
    // do something in A
    resolve();
}).then(function(result) {
    // do something else in B
    return result;
})