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

Using JQuery $.when with dynamic number of requests

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

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

可以遍历 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
      }          
    });
});

同样可以创建一个基于arguments.length

for循环

DEMO