我有一个如下所示的简化函数:
function(query) {
myApi.exec('SomeCommand', function(response) {
return response;
});
}
基本上我希望它调用 myApi.exec
,并返回在回调 lambda 中给出的响应。但是,上面的代码不起作用,只是立即返回。
只是为了一个非常骇人听闻的尝试,我尝试了以下没有用的方法,但至少你明白我想要实现的目标:
function(query) {
var r;
myApi.exec('SomeCommand', function(response) {
r = response;
});
while (!r) {}
return r;
}
基本上,什么是“node.js/event 驱动”的好方法?我希望我的函数等到回调被调用,然后返回传递给它的值。
最佳答案
执行此操作的“良好的 node.js/事件驱动”方式是不等待。
在使用像 Node 这样的事件驱动系统时,与几乎所有其他事情一样,您的函数应该接受一个回调参数,该参数将在计算完成时被调用。调用者不应等待正常意义上的“返回”值,而是发送将处理结果值的例程:
function(query, callback) {
myApi.exec('SomeCommand', function(response) {
// other stuff here...
// bla bla..
callback(response); // this will "return" your value to the original caller
});
}
所以你不要这样使用它:
var returnValue = myFunction(query);
但是像这样:
myFunction(query, function(returnValue) {
// use the return value here instead of like a regular (non-evented) return value
});
关于javascript - 如何使函数等到使用 node.js 调用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010288/