使用带有动态请求数的JQuery $ .when

时间:2015-07-19 00:51:20

标签: jquery ajax callback get promise

我正在使用动态数量的.get请求。等待它们完成以便我可以处理所有响应

// function that returns the response of a get request
function getRecipe(recipeID){            
  var url2 = 'https://api.pearson.com/kitchen-manager/v1/recipes/'+recipeID;
  return $.get(url2);
}

// function that loops through an unknown sized array and calls the getRecipe function for each one and adds the request to a requests array
function getAllRecipes(recipes_array){
  var requests = [];
  for (var i = 0; i < recipes_array.length; i++) {
    var recipeID = recipes_array[i];
    requests.push(getRecipe(recipeID));
  } 

  // this is where I would like to wait for all of the requests to come back so I am trying to use $.when

}

如果没有动态数量的请求,我会将其构造成像这样的

    $.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
       // v1, v2, and v3 are the return responses from each request
    });

v1,v3和v3应该是每个请求的返回值

我试过以下但没有运气......

  $.when(requests).done(function(stuff) {

    // stuff returns an array of the correct number of objects but not the returned values, just objects
    // $.type(stuff[0]) == object
  }

以及......

  $.when.apply($, requests).then(function(stuff) {
    // stuff returning 3 items in an array
    // item 1 is the response from the last request
    // item 2 is a string "success"
    // item 3 is an object

  }

如何在动态时访问所有请求响应?

我引用了以下内容来实现这一目标:

Wait until all jQuery Ajax requests are done?

How do you work with an array of jQuery Deferreds?

1 个答案:

答案 0 :(得分:1)

可以遍历arguments并且每个ajax调用都包含一个数组。这样您就不需要知道有多少请求了

$.when.apply(null,requests).then(function(){
    // in javascript arguments  exposed by default and can be treated like array
    $.each(arguments, function(i,row){
      var status = row[1], data = row[0];
      if(status === 'success'){
        //do something with data
      }          
    });
});

同样可以基于for

创建arguments.length循环

DEMO