为了简化我的问题,我对代码做了一些修改。我现在可以从回调函数中获取值,我现在想将此数据传递到变量中。
Javascript
如何让 PostInformation 返回参数?
function AjaxRequest(callback) {
var hasErrors = false;
dojo.xhrPost({
url: 'hello',
content: SomeData,
load: function (formErrors) {
//preform some operation
//set hasErrors to true
hasErrors = true;
if (typeof callback === "function") callback(hasErrors);
},
error: function (e) {
console.log(e + ' page not posted error');
}
});
}
function PostInformation() {
try {
AjaxRequest(function (args) {
console.log('The hasErrors is ' + args);
return args;
});
} catch (e) {
console.log(e);
}
}
最佳答案
您在发送请求时调用 handleServerResponse
,而不是在回调中。应该是:
var doesErrorsExist = postToServer(function() {
handleServerResponse(containers, function (args) {
return args;
});
});
但这仍然行不通——异步函数永远无法向其调用者返回值,因为在函数返回后操作完成之前该值不会存在。
我没有试图弄清楚你想做的所有事情的逻辑,所以我没有关于如何解决这个问题的具体建议。我认为如果您重读链接到的问题,您应该会获得更多见解。
关于javascript - 从嵌套回调函数中提取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23226215/