for循环中的AngularJS异步请求

AngularJS asynchronous requests in a for loop

本文关键字:异步 请求 AngularJS 循环 for      更新时间:2023-09-26

我显示了一个列表,每个项都包括一个引用其他文档的id数组(mongodb(。当用户点击一个项目时,我想用实际的文档填充数组(=用相应的对象替换id(。

我的问题是,一旦请求完成,数据就不会应用到数组中的正确位置。随着for循环的进行,我在回调函数中移交的索引可能会增加。当请求准备好时,for循环可能已经完成,因此结果会附加到数组的末尾,而不是其原始位置。我尝试使用angular.copy((深度复制索引,尽管我认为这应该没有必要。我甚至不确定int是对象还是平面数据类型,谷歌的一项小型研究并没有给出明确的答案。

我能够在一次重击中重新制造出这个问题。

我以前遇到过类似的问题,但能够解决它,但这次我不知道如何处理这个问题。有什么提示吗?

您需要通过将当前迭代的i传递到fetchSubItem()来正确捕获它。。。

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

Plunker: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." );
}