I'm having a bit of trouble with jQuery Deferred.
I'm using a jQuery ajax call inside a function wrapper, and I'm attempting to chain two success callbacks one after the other, in order of scope. However, both success callbacks are executing simultaneously, which is causing problems.
My initial function call looks like this (system.log is a smarter console.log.):
serverpaths.setConfig(path).then(system.log("BAM! SERVERPATHS: " + serverpaths));
Inside this setConfig method, I have an AJAX call with a .then() chained to it. (system.defer is a wrapper that returns a jQuery.Deferred object; http.get is a wrapper for jQuery.ajax.)
config.setConfig = function (configObj) {
var that = this;
var inlineHelper = function (data) {
return system.defer(function (dfd) {
for (var key in data) {
system.log("Config[" + key + "]: " + that[key]);
system.log("Data[" + key + "]: " + data[key]);
that[key] = data[key];
system.log("New Config[" + key + "]: " + that[key]);
}
}).promise();
};
if (typeof configObj === "string") {
http.get("api/getPathConfig") // The problem seems to be in this area
.then(function (data) {
return system.defer(function () {
inlineHelper(data);
}).promise();
});
} else {
return system.defer(function () {
inlineHelper(configObj);
}).promise();
}
};
Ideally, the ajax request should be called, then inlinehelper should be called, then system.log should be called, because I'm kicking my promise object back up the chain with return statements. The problem here is that the ajax request is called, and then system.log and inlinehelper are called simultaneously.
Has anyone run into a problem like this before? Function scope and async calls seem to be fighting each other here. I'm sure I can figure this out, but it doesn't seem quite logical - my guess is that when my ajax request fires its success, that triggers the .then() call in my main scope without me wanting it to. I'm sure I could solve this, but it helps to have a great community of devs to bounce thoughts off of.
I appreciate all of your advice. Thank you!