簡體   English   中英

循環中的AngularJS異步請求

[英]AngularJS asynchronous requests in a for loop

我顯示一個列表,每個項目都包含一個引用其他文檔(mongodb)的ID數組。 當用戶單擊某個項目時,我想用實際文檔填充數組(=用相應的對象替換ID)。

我的問題是,一旦請求完成,數據就不會應用於數組中的正確位置。 隨着for循環的進行,我在回調函數中提供的索引可能會增加。 在請求准備就緒時,for循環可能已經完成,因此結果將附加到數組的末尾而不是原始位置。 我嘗試使用angular.copy()深度復制索引,盡管我認為這沒有必要。 我什至不確定int是對象還是平面數據類型,Google的一項小型研究並未給出明確的答案。

我能夠用一個笨拙的人重新創建問題。

我之前遇到過類似的問題,但可以解決此問題,但是這次我不確定如何處理此問題。 有什么提示嗎?

您需要通過將其傳遞給fetchSubItem()來為當前迭代正確捕獲i ...

for( var i=0; i < item.subItems.length; i++ ) {
    // in the real world app fetchSubitem does an http api call
    fetchSubItem( item.subItems[i], i, function(result, i){
      // this happens long after the for loop and all finished
      item.subItems[i] = result;
    });
}

// ....

function fetchSubItem ( id, j, callback ) {
    var found = false
    for( var i=0; i < sideList.length; i++ ) {
      if ( sideList[i].id == id ) {
        found = true;
        $timeout( function(){ callback( sideList[i], j ); }, 1000 ); // to simulate asynchronicity
        break;
      }
    }
    if ( !found ) callback( "SubItem "+id+" not found.", j );
}

柱塞: http ://plnkr.co/edit/8qTNUwjyWYrokc1bTXLI?p=preview

異步調用在被調用時將采用值“ i”。 因此,您需要編寫一個輔助函數來保存i的值。 這樣的事情應該起作用。

function fetchSubItem ( id, callback ) {
    function helper(i) {
        $timeout( function(){ callback( sideList[i] ); }, 1000 ); // to simulate asynchronicity
    }

    var found = false

    for( var i=0; i < sideList.length; i++ ) {
        if ( sideList[i].id == id ) {
            found = true;
            helper(i);
            break;
        }
    }
    if ( !found ) callback( "SubItem "+id+" not found." );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM