2015-07-19 19 views
1

我有我使用。當不用彷徨請求的動態數量的動態數量的等待,直到他們完成,這樣我可以與所有他們的反應的工作

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

+0

的最後一個版本看起來OK創建基於for循環(雖然它的不清楚你是否真的想'then'或者'done'是否足夠),但'requests'的內容究竟是什麼?你是否證實了正確的價值? – Jon

+0

@Jon'stuff'只會保留第一個請求 – charlietfl

回答

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

同樣可以在arguments.length

DEMO

+0

謝謝@charlietfl這就是我需要的!你知道在這種情況下哪裏有參數的文檔? – MicFin

+0

@MicFin並不是真的......似乎還缺少很多這類答案。請記住,如果您不確定參數中包含什麼,可以對任何函數執行此操作 – charlietfl