I need to make a series of N ajax requests without locking the browser, and want to use the jquery deferred object to accomplish this.
Here is a simplified example w
I know I'm late to this, but I believe your original code is mostly fine but has two (maybe three) problems.
Your getData(country)
is being called immediately because of how you coded your pipe's parameter. The way you have it, getData()
is executing immediately and the result (the ajax's promise, but the http request begins immediately) is passed as the parameter to pipe()
. So instead of passing a callback function, you're passing an object - which causes the pipe's new deferred to be immediately resolved.
I think it needs to be
deferred.pipe(function () { return getData(country); });
Now it's a callback function that will be called when the pipe's parent deferred has been resolved. Coding it this way will raise the second problem. None of the getData()s will execute until the master deferred is resolved.
The potential third problem could be that since all your pipes would be attached to the master deferred, you don't really have a chain and I'm wondering if it might execute them all at the same time anyways. The docs say the callbacks are executed in order, but since your callback returns a promise and runs async, they might all still execute somewhat in parallel.
So, I think you need something like this
var countries = ["US", "CA", "MX"];
var deferred = $.Deferred();
var promise = deferred.promise();
$.each(countries, function(index, country) {
promise = promise.pipe(function () { return getData(country); });
});
deferred.resolve();