Here is some code.
function callServiceSync(url, obj) {
var result = true;
callServiceOptions(url, obj, function(res){
result = res;
alert("RESULT CB: "+JSON.stringify(result));
}, {async: false});
alert("RESULT POST-CB: "+JSON.stringify(result));
return result;
}
When it runs, the alert box says:
RESULT CB: {"success":true,"data":"dtrombley"}
(that's what the webservice returns, in reality), and then:
RESULT POST-CB: true
Why isn't this assignment to the closure variable working? Am I misunderstanding how JS closures work?
callServiceOptions() is rather longwinded - but the gist of it is that it calls jQuery's $.ajax method with it's last arguments options extended into some default (in this case, async is disable for sync query), and then executes the provided callback.
Is $.ajax() maybe executing something in some kind of way that disables/screws up closures (but I call the cb, not $.ajax()!)? If so, how to fix that?
For completeness (though really this function shouldn't be able to screw things up to my thinking):
function callServiceOptions(url, obj, cb, options) {
optSuccess = options.success;
optError = options.error;
opts = {}
$.extend({},options)
if (!opts.contentType) {
opts.contentType = "application/json";
}
if (!opts.dataType) {
opts.dataType = "json";
}
if (!opts.data && obj) {
opts.data = JSON.stringify(obj);
}
if (!opts.processData) {
opts.processData = false;
}
if (!opts.method) {
opts.method = "POST";
}
opts.error = function(jqXHR, textStatus, errorThrown) {
if (optError) {
optError(jqXHR, textStatus, errorThrown);
}
if (jqXHR.responseText) {
responseObj = JSON.parse(jqXHR.responseText)
if (responseObj && responseObj.message)
cb({
success: false,
message: responseObj.message
})
return
}
cb({
success: false,
message: errorThrown
});
};
opts.success = function(data, textStatus, jqXHR) {
if (optSuccess) {
optSuccess(data,textStatus,jqXHR);
}
cb(data);
};
if (url.charAt(0) == '/') {
url = url.substr(1);
}
opts.url = WEBCTX.getBaseURL() + url;
$.ajax(opts);
}
This is not a duplicate of any question asking how to return a value from an async event. I have a working callServiceAsync() which does that beautifully. I am using synchronous mode, if you aren't familiar with it, please take a pass on this question...