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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…