无法从Javascript回调获取返回值 [英] Having trouble getting a return value from a Javascript callback
问题描述
嘿,大家 - 我有一些困难正确地从我的一个Javascript回调函数获取返回值,它看起来是依赖于竞争条件,但我不确定:
Hey everyone - I'm having some difficulties properly getting a return value from one of my Javascript callback functions, and it looks to be dependent on a race condition, but I'm not sure:
JSOBJ.container = function() {
return {
getName: function() {
var value;
companyfn.app.getInfo(callback);
function callback(foo) {
// alert("gets here");
if (foo.hadError()) {
alert("Error found!");
} else {
value = foo.getField(companyfn.app.Field.SUB_DOMAIN);
}
// alert('callback: ' + value);
}
return value;
}
}
}();
JSOBJ.main = function () {
return {
init: function() {
alert(JSOBJ.container.getName());
}
};
}();
在JSOBJ.main.init();上面,我试图得到正确的值,但是当我运行我的代码,我几乎总是得到一个未定义的返回值。当我取消注释JSOBJ.container.getName()中的alert语句时,getName函数似乎在不调用回调的情况下运行,警报弹出,然后getName函数被调用。所以它感觉像一个竞争条件,我想说它必须与闭包,但我不知道如何正确实现它,所以它等待getField返回一个值。
In JSOBJ.main.init(); above, I'm trying to get the proper value, but when I run my code, I almost always get a return value of undefined. When I uncomment my alert statements in JSOBJ.container.getName(), the getName function seems to run without invoking the callback, the alert pops up, and then the getName function gets called. So it feels like a race condition, and I want to say it has to do with closures, but I'm not sure how to implement it properly so it "waits" for getField to return a value. Can anyone help?
推荐答案
你不能让你的功能块,直到回调完成,而不完全冻结浏览器,这是
You cannot make your function block until the callback finishes without completely freezing the browser, which is not a good idea.
您需要让 getName
函数接受回调,并给出回调其值,就像 companyfn.app.getInfo
。
You need to make your getName
function take a callback and give the callback its value, just like companyfn.app.getInfo
.
这篇关于无法从Javascript回调获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!