I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.
I share an easy example that could help you to handle multiple requests and their responses:
var arr = [
$.ajax({url:"test1.php"}),
$.ajax({url:"test2.php"}),
$.ajax({url:"test3.php"})
];
$.when.apply( undefined, arr ).then(function() {
var objects=arguments;
console.dir(objects);
});
The arguments to $.when
should be the return value of $.ajax
, which also doesn't need to be called separately -- that makes no sense. You want something like this:
for (i = 0; i < list.length; i++) {
requests.push($.ajax(...));
}
$.when.apply(undefined, requests).then(...)
The reason that .apply
is needed is because $.when
can take multiple arguments, but not an array of arguments. .apply
expands essentially to:
$.when(requests[0], requests[1], ...)
This also assumes that the requests can be completed in any order.
http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.