.When()和.done()使用带有.done的数组 [英] .When() and .done() using an array with .done

查看:67
本文介绍了.When()和.done()使用带有.done的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Google内容脚本,并且我的程序需要对服务器进行大约30次AJAX调用.我将JQuery的.when函数与.apply结合使用,以将数组传递给.when函数.我还使用.done,希望传递一个参数数组,该参数将采用.when函数的延迟对象.有什么办法吗?这就是我想要做的.

I am writing a google content script and my program needs to make roughly 30 AJAX calls to the server. I am using JQuery's .when function in conjunction with .apply to pass in an array to the .when function. I am also using .done and I want to be able to pass in an array of arguments that will take on the deferred objects from the .when function. Is there any way to do this? This is what I am trying to do.

    var callback = function(a) {
  console.log("done", a);
};
var requests = [];
var requestArray = [];
  for(i = 0; i < liclass.length; i++) {
  requests.push($.ajax({
      url: liclass[i],
     success: function() {;
      }
    }));
            var str = "messageArg" + i
        requestArray.push(str)
  }

$.when.apply($, requests).done(function(requestArray){
callback(requestArray)});

推荐答案

如果您查看示例, $.when ,您会看到回调传递了每个promise的参数.如果该承诺来自Ajax调用,则每个参数都是[ data, statusText, jqXHR ]形式的数组.

If you look at the examples for $.when, you see that the call back gets passed an argument for each promise. If that promise came from an Ajax call, then each argument is an array of the form [ data, statusText, jqXHR ].

因此,您只需要遍历参数并提取第一个元素. $.map非常简单:

So you you just have iterate over the arguments and extract the first element. $.map makes that very easy:

$.when.apply($, requests)
  .then(function() {
    return $.map(arguments, function(v) {
      return v[0];
    });
  })
  .done(callback);

这篇关于.When()和.done()使用带有.done的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆