Reputation: 986
I have a function that returns a promise as follows:
var loadLimits = function (url, arr, carrier) {
var rdata = {
carrierId: carrier
};
var deferred = new $.Deferred();
var xhr = $.get(apiHost + url, rdata);
xhr.done(function (data) {
arr.removeAll();
for (var i = 0; i < data.length; i++) {
var newItem = new LimitItem(data[i].Id, data[i].LimitText, data[i].ILF, data[i].ApprovalRequired);
arr().push(newItem);
};
deferred.resolve();
});
xhr.fail(function () {
deferred.reject();
});
return deferred.promise();
};
I'm calling that function from within another function as follows:
var promise = loadLimits(url, limitsArray, carrierId);
promise.done(self.nextFunction());
Why is my code firing self.nextFunction before the promise resolves? Eventually the promise DOES resolve successfully, so its not an ajax fail event. I'm using jQuery 1.9.1 and I'm testing with Chrome.
Thanks for any help
Upvotes: 0
Views: 973
Reputation: 196296
Use either
promise.done(self.nextFunction);
or
promise.done(function(){ self.nextFunction(); });
Your code immediately executes that function, instead of passing it as a reference/callback to be executed later.
Upvotes: 1