AngularJS for循环中的异步请求

时间:2014-03-18 03:15:24

标签: javascript arrays angularjs mongodb asynchronous

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

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

I was able to re-create the problem in a plunkr.

之前我遇到过类似的问题,但是能够解决它,但这次我不知道如何处理这个问题。任何提示?

2 个答案:

答案 0 :(得分:1)

您需要通过将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 ); }

{{1}}

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

答案 1 :(得分:0)

异步调用将假设&#39; i&#39;在它被调用时。因此,您需要编写一个辅助函数来保存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." );
}
相关问题