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 with three requests, but my program may need to queue up over 100 (note that this is not the exact use case, the actual code does need to ensure the success of step (N-1) before executing the next step):
$(document).ready(function(){
var deferred = $.Deferred();
var countries = ["US", "CA", "MX"];
$.each(countries, function(index, country){
deferred.pipe(getData(country));
});
});
function getData(country){
var data = {
"country": country
};
console.log("Making request for [" + country + "]");
return $.ajax({
type: "POST",
url: "ajax.jsp",
data: data,
dataType: "JSON",
success: function(){
console.log("Successful request for [" + country + "]");
}
});
}
Here is what gets written into the console (all requests are made in parallel and the response time is directly proportional to the size of the data for each country as expected:
Making request for [US]
Making request for [CA]
Making request for [MX]
Successful request for [MX]
Successful request for [CA]
Successful request for [US]
How can I get the deferred object to queue these up for me? I've tried changing done to pipe but get the same result.
Here is the desired result:
Making request for [US]
Successful request for [US]
Making request for [CA]
Successful request for [CA]
Making request for [MX]
Successful request for [MX]
Edit:
I appreciate the suggestion to use an array to store request parameters, but the jquery deferred object has the ability to queue requests and I really want to learn how to use this feature to its full potential.
This is effectively what I'm trying to do:
when(request[0]).pipe(request[1]).pipe(request[2])... pipe(request[N]);
However, I want to assign the requests into the pipe one step at a time in order to effectively use the each traversal:
deferred.pipe(request[0]);
deferred.pipe(request[1]);
deferred.pipe(request[2]);
See Question&Answers more detail:os