问题描述
我有一个看起来像这样的简化函数:
I have a simplified function that looks like this:
function(query) {
myApi.exec('SomeCommand', function(response) {
return response;
});
}
基本上我希望它调用 myApi.exec
,并返回回调 lambda 中给出的响应.但是,上面的代码不起作用,只是立即返回.
Basically i want it to call myApi.exec
, and return the response that is given in the callback lambda. However, the above code doesn't work and simply returns immediately.
只是为了一个非常黑客的尝试,我尝试了下面的方法但没有用,但至少你明白我想要实现的目标:
Just for a very hackish attempt, i tried the below which didn't work, but at least you get the idea what i'm trying to achieve:
function(query) {
var r;
myApi.exec('SomeCommand', function(response) {
r = response;
});
while (!r) {}
return r;
}
基本上,有什么好的node.js/事件驱动"方式来解决这个问题?我希望我的函数等到回调被调用,然后返回传递给它的值.
Basically, what's a good 'node.js/event driven' way of going about this? I want my function to wait until the callback gets called, then return the value that was passed to it.
推荐答案
好的 node.js/event 驱动"方法是不要等待.
The "good node.js /event driven" way of doing this is to not wait.
与使用事件驱动系统(如节点)时的几乎所有其他内容一样,您的函数应该接受一个回调参数,该参数将在计算完成时被调用.调用者不应等待正常意义上的值返回",而是发送将处理结果值的例程:
Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:
function(query, callback) {
myApi.exec('SomeCommand', function(response) {
// other stuff here...
// bla bla..
callback(response); // this will "return" your value to the original caller
});
}
所以你不要这样使用它:
So you dont use it like this:
var returnValue = myFunction(query);
但是像这样:
myFunction(query, function(returnValue) {
// use the return value here instead of like a regular (non-evented) return value
});
这篇关于如何使函数等待直到使用 node.js 调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!