【问题标题】:How to make jQuery wait until all get() requests in each() get done如何让 jQuery 等到 each() 中的所有 get() 请求完成
【发布时间】:2021-09-01 14:08:20
【问题描述】:

我有一个数组,里面有一些 URL,我想获取它们的 HTML 并将其推送到另一个数组(或 JSON 或其他东西)中。

代码如下所示;

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
};

问题是这段代码不会等待 ajax() 请求并开始发送 received_data 空。如何等到所有 ajax() 请求结束(使用同步请求除外)?

【问题讨论】:

标签: jquery ajax


【解决方案1】:

你可以使用$.ajax的返回值作为Promise,并等待它们全部使用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
    });
};

$.when 的调用看起来有点古怪,因为它期望接收一系列Promises 来等待作为离散参数,而不是一个数组,所以我们使用Function#apply 来做到这一点。如果您要经常这样做,您可能需要扩展 jQuery:

(function($) {
    $.whenAll = function() {
        return $.when.apply($, arguments);
    };
})(jQuery);

那么你的使用就变成了:

$.whenAll(gets).then(function() {
    // send received_data to some other server
});

旁注:我假设在您的真实代码中上面的 function 一词前面有一些东西(例如,f = functionf: function 如果它在对象文字中)。否则,它是一个无效的函数声明,因为它没有名称。 (如果你确实有一些东西,它就是一个有效的匿名函数表达式。)

【讨论】:

  • 是的,在实际代码中,我的函数有一个名称,这有点像复制粘贴错误。很抱歉。
猜你喜欢
  • 2014-07-14
  • 2020-03-17
  • 1970-01-01
  • 2013-01-24
  • 2015-04-17
相关资源
最近更新 更多