Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

ajax - How to make jQuery wait until all get() requests in each() get done

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...