2014-04-02 26 views
0
function hello() { 
    var arr = []; 
    $.get(url, function (data) { 
     var items = $(data).find("item"); 
     $(items).each(function (idx, item) { 
     arr.push(item); 
     }); 
    }); 
    return arr; //undefined because nested loops are not finished processing. 
} 

如何在返回之前確保arr已填充?在嵌套異步功能完成時做些事

+2

爲什麼downvote? – GoodSp33d

回答

1

無法從異步調用中轉義。您需要回調才能獲得GET調用的結果。

function asynCall() { 
    var response; 
    // Ajax call will update response here later. 
    return response; 
} 
var responseFromFun = asyncCall(); // This will be undefined or null. 

這就是您的代碼現在的工作方式。所以響應總是undefinednull

爲了獲得來自Ajax調用的響應,在調用它時將回調傳遞給該函數,而不是爲其分配響應。

function asyncCall(callBack) { 
    var response; 
    $.get(...) { 
     response = someValueReturnedFromServer; 
     callBack(response); 
    } 
    // There wont be a return here 
} 
asyncCall(function(response){ 
    // Do something with response now 
}); 

這裏的缺點是,如果你正在傳遞arr對象(在代碼中)到一些其他功能,甚至要改變使用回調!

+0

嘿謝謝你。在我遇到這個問題之前,我想我實際上並沒有理解回調是如何構建的。現在我知道了!還有一個問題需要補充。爲什麼有必要檢查回調函數是否像'typeof callback =='function''那樣在其他一些與回調相關的帖子中看到? –

+1

@MaximusS它只是爲了確保函數確實通過了,而不是數字或任何東西。在上面的代碼中,'asyncCall(「hello」)'也是有效的,但當'get'調用完成時會導致錯誤,因爲沒有完成錯誤處理。 – GoodSp33d