I have a series of asynchronous actions whose responses must be synchronized in order to run a final action. I'm using The Deferred object and the when() and done() methods to achieve this, but for some reason, the final action within done() is always executed when the first resolve() of the responses is invoked.
This is the code I have, cut a bit short to make it clearer:
// Central function that creates a Deferred object and returns a
// Promise from it. when the passed request is done,
// the Deferred is resolved
var getData = function(url, successFunction) {
var deferred = $.Deferred();
$.ajax({
url: url,
method: 'get',
dataType: 'json'
}).done(function(p) {
successFunction(p);
deferred.resolve(p);
}).fail(function(p){
deferred.reject(p);
});
return deferred.promise();
};
// Success actions to be called for each asynchronous request
var populateDestinations = function(data) {
// synchronous actions on DOM
};
var populateTaxes = function(data) {
// synchronous actions on DOM
};
var populatePayment = function(data) {
// synchronous actions on DOM
};
// Actions that return a Promise to control the resolution of
// all the deferred objects
var getCustomerDestinations = function(customerId) {
var url = $modal.data('url_destinations') + customerId;
return getData(url, populateDestinations);
};
var getCustomerTaxes = function(customerId) {
var url = $modal.data('url_taxes') + customerId;
return getData(url, populateTaxes);
};
var getCustomerPayment = function(customerId) {
var url = $modal.data('url_payment') + customerId;
return getData(url, populatePayment);
};
var populateFields = function() {
// final actions
};
$.when(getCustomerDestinations(customer_id),
getCustomerTaxes(customer_id),
getCustomerPayment(customer_id))
.done(function(){
populateFields();
});
populateFields() is being called whenever one of the "promised" functions is resolved, not when all of them are resolved.
Any idea what I'm doing wrong? Maybe I haven't yet grasped the concept of the Deferred object.