保持Node.js异步的麻烦

时间:2013-01-08 06:43:12

标签: node.js asynchronous event-loop

所以,我今天遇到了一种情况,我需要将异步数据库调用放入我的自定义函数中。例如:

function customfunction(){
    //asynchronous DB call
}

然后我从我的程序中的另一个点打电话。首先,为了安全起见,这仍然是异步的吗? (我会假设这是为了继续我的问题)。我想从这里做的是在完成异步数据库调用时调用另一个特定函数。我知道DB调用将在完成时触发回调函数,但问题是这个自定义函数非常通用(意味着它将从我的代码中的许多不同点调用),所以我不能在回调中放置特定的方法调用功能,因为它不适合所有情况。如果我不清楚我在说什么,我将在下面举例说明我喜欢做什么:

//program start point//
customfunction();
specificfunctioncall(); //I want this to be called DIRECTLY after the DB call finishes (which I know is not the case with this current setup)
}

function customfunction(){
    asynchronousDBcall(function(err,body){
    //I can't put specificfunctioncall() here because this is a general function
    });
}

如何让上述情况发挥作用?

感谢。

2 个答案:

答案 0 :(得分:4)

您就是这样做的:

//program start point//
customfunction(specificfunctioncall);

并在customfunction()中:

function customfunction(callback){
    asynchronousDBcall(function(err,body){
        callback();
    });
}

函数只是可以像字符串和数字一样传递的数据。事实上,使用匿名函数包装器function(){...},您可以将 CODE 视为可以传递的数据。

因此,如果您希望在完成DB调用而不是函数时执行某些代码,请执行以下操作:

customfunction(function(){
    /* some code
     * you want to
     * execute
     */
});

答案 1 :(得分:1)

周杰伦 如果asyncDbCall是数据库库函数,那么它将具有回调函数作为其参数之一(如果它是真正的异步函数)。将specificFunctionCall作为参数传递给该函数,您就完成了。

function CustomFunction{
  asyncDbCall(.....,specificFunctionCall);
}

现在在调用CustomFunction时,它将调用asyncDbCall函数,一旦完成,asyncDbCall将自动调用你的回调函数。