The solution is not to use $.when
to start the chain of calls:
service.doCall('GET', 'customers').then(function() {
return service.doCall('GET', 'shifts')
}).then(function() {
return service.doCall('GET', 'params')
}).then(function() {
return service.doCall('GET','columns')
}).then(...)
Note that this won't give you the benefit of $.when
then automatically being called with all four results, so whilst you shouldn't use $.when
to start the calls, you can use it to create an additional promise that when resolved will be passed the results of all previous calls.
var def = [];
def[0] = service.doCall('GET', 'customers');
def[1] = def[0].then(function() { return service.doCall('GET', 'shifts') } );
def[2] = def[1].then(function() { return service.doCall('GET', 'params') } );
def[3] = def[2].then(function() { return service.doCall('GET', 'columns') } );
$.when.apply($, def).then(function(customers, shifts, params, columns) {
...
});
In this case I create an array of deferred objects, but each successive AJAX call isn't started until the previous one has finished. It then uses $.when.apply($, def)
to pass all four deferred object results to the final callback.