0

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) ?

tomoari
  • 35
  • 2
  • 5
  • possible duplicate of [jQuery Deferred - waiting for multiple AJAX requests to finish](http://stackoverflow.com/questions/6538470/jquery-deferred-waiting-for-multiple-ajax-requests-to-finish) – Gabriele Petrioli May 13 '13 at 14:39

1 Answers1

10

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 Promises 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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • And yes, in the actual code my function has a name, that one was sort of a copy-paste mistake. Sorry for that. – tomoari May 13 '13 at 14:52