Reputation: 35
I have an array with some URLs inside, and I want to get their HTML and push it into another array (or JSON or something else).
The code looks like this;
url = ["/page_1.html", "/page_2.html"];
received_data = [];
function() {
url.each(function(i) {
$.ajax({
type: 'GET',
url: this,
success: function(data) {
received_data.push(data);
}
});
});
// send received_data to some other server
};
The problem is that this code will not wait for the ajax() requests and start sending received_data empty. How to wait until all ajax() requests end (except using synchronous requests) ?
Upvotes: 0
Views: 2903
Reputation: 1074989
You can use the return value of $.ajax
as a Promise
, and wait for all of them to be fulfilled using jQuery.when
:
function() {
var gets = [];
url.each(function(i) {
gets.push($.ajax({
type: 'GET',
url: this,
success: function(data) {
received_data.push(data);
}
}));
});
$.when.apply($, gets).then(function() {
// send received_data to some other server
});
};
The call to $.when
looks a bit funky because it's expecting to receive the series of Promise
s to wait for as discrete arguments, rather than an array, so we use Function#apply
to do that. If you're going to do this a lot, you might want to extend jQuery a bit:
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
Then your use becomes:
$.whenAll(gets).then(function() {
// send received_data to some other server
});
Side note: I assume there's something in front of the word function
above in your real code (e.g., f = function
, or f: function
if it's in an object literal). Otherwise, it's an invalid function declaration as it has no name. (If you do have something, it's a valid anonymous function expression.)
Upvotes: 10