0

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

function customfunction(){
    //asynchronous DB call
}

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

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

我怎样才能使上述情况起作用?

谢谢。

4

2 回答 2

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
     */
});
于 2013-01-08T07:19:22.140 回答
1

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

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

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

于 2013-01-08T07:00:31.223 回答