我正在編寫一些JavaScript/jQuery代碼,它要求我向各種API發出大量請求。我多次遇到這個問題,這只是一個實例的基本例子。使用回調函數和異步請求時避免重複
該代碼向服務器發出異步請求,然後如果不符合返回數據的條件,代碼將發出另一個請求。第二個請求有一個回調,其中包含許多與其父代相同的邏輯。我知道我通過在每個回調中調用returnFunction
來避免重複,但是有沒有辦法完全避免這種情況?
var container = [];
$.getJSON("http://www.url.com/api/?callback=?",
{ data: "mydata" },
function(data) {
if(!data.length) {
// No results
} else {
// Put the results into an array
$(data).each(function(k, v){
container.push(v.some_data);
});
// If the query did not return enough results
if(data.length < limit) {
var number_missing = limit - data.length;
// Get some more results and append to the array
myFunctionToGetSomethingElse(number_missing, function(response){
// Add these results to the array
$(response).each(function(k, v){
container.push(v.some_data);
});
// Do something with this data
returnFunction(response);
});
} else {
// Do something with the result
returnFunction(data);
}
}
});
你會如何建議我避免重複回調中的代碼?這是唯一可行的方法嗎?
接受你的答案的詳細信息。雖然tomg的回答非常有幫助!看起來像一個非常酷的工具。 – betamax 2010-09-23 08:38:14