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

时间:2016-05-23 19:33:52

标签: node.js mongodb asynchronous callback underscore.js

所以我想要的是,

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)

2 个答案:

答案 0 :(得分:2)

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

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

}

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

或者,您可以使用承诺。

答案 1 :(得分:2)

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

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