要简化我的问题,我做了一些修改code。我现在可以从回调函数中获得的价值现在我想将这个数据传递到一个变量。
Javascript的
我怎样才能PostInformation返回的args?
函数AjaxRequest(回调){
VAR hasErrors = FALSE;
dojo.xhrPost({
网址:'你好',
内容:SomeData,
负载:功能(formErrors){
// preform一些操作
//设置hasErrors为真
hasErrors = TRUE;
如果(typeof运算回调===功能)回调(hasErrors);
},
错误:函数(E){
的console.log(E +页面不贴错误');
}
});
}
功能PostInformation(){
尝试 {
AjaxRequest(函数(参数){
的console.log('的hasErrors是'+参数);
返回ARGS;
});
}赶上(五){
执行console.log(E);
}
}
解决方案
您正在呼叫 handleServerResponse
当你发送请求,而不是回调。它应该是:
VAR doesErrorsExist = postToServer(函数(){
handleServerResponse(集装箱,函数(参数){
返回ARGS;
});
});
但是,这仍然是行不通的 - 异步函数永远不能返回一个值,它的调用者,因为该值将不存在,直到函数返回后的操作完成
我没有试图找出一切你正在试图做的逻辑,所以我没有一个具体的建议,关于如何解决这个问题。我认为,如果你重读您链接到的问题,你应该得到一些更深入的了解。
To simplify my question i did some modifications to the code. I am now able to get the value from the callback function i now want to pass this data into a variable.
Javascript
How can i get PostInformation to return args?
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);
}
}
解决方案
You're calling handleServerResponse
when you send the request, not in the callback. It should be:
var doesErrorsExist = postToServer(function() {
handleServerResponse(containers, function (args) {
return args;
});
});
But this still won't work -- an asynchronous function can never return a value to its caller, because the value won't exist until the operation completes after the function returns.
I haven't tried to figure out the logic of everything you're trying to do, so I don't have a concrete suggestion for how to fix that. I think if you reread the question you linked to, you should get some more insight.