Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...