如何在javascript中获得响应后逐个执行for循环?

时间:2016-08-09 16:15:34

标签: javascript angularjs arrays for-loop foreach

JAVASCRIPT

for (var i=0; i<$scope.length; i++)
{
    var data = {
        page_no:i
    };
    newlocalitemService.list(data, function(res) { 
        $scope.data.push(res);
   });
}

newlocalitemService

list: function(data,success,error){
    $http({
        url: CONFIG.apiUrl + '/items',
        method: "GET",
        params: data
        }).success(success).error(error);
}

我在for循环中调用API。如何在获得响应后调用每个API。这里$ scope.data初始化为数组,API是异步方法。

2 个答案:

答案 0 :(得分:1)

某种递归函数,它会调用自身直到集合结束:

function doStuff(arr, idx) {
    if (idx <= (arr.length - 1)) {
        newlocalitemService.filter(arr[idx], function(res) { 
            $scope.data.push(res);
            doStuff(arr, ++idx);
        });
    }
}

doStuff($scope.data, 0);

答案 1 :(得分:0)

一旦你检索了AJAX数据,就需要在回调函数中插入for循环,就像这样(在JQuery中):

Create Database MyDb On
( FileName = N'F:\MSSQL13.SS\MSSQL\UserData\MyDb.mdf' ),
( FileName = N'F:\MSSQL13.SS\MSSQL\UserLogs\MyDb_log.ldf' )

 For Attach
    With FileStream ( Directory_Name = 'F:\MSSQL13.SS\MSSQL\UserData\MyDb-Hekaton' )