Angularjs for loop承诺回调

时间:2015-03-17 09:29:03

标签: angularjs http

我想知道是否有可能在一系列请求结束时收到回调。我附上了一个示例代码,以便您更好地理解:

for (var i = 0; i < $scope.array.length; i++) {
    factory.getX($scope.array[i].id)
        .success(function (_response) {
            /* call function if it's the last request in the for loop*/
        })
        .error(function (_err) {
            $scope.displayAlert(_err)
        })
}

在工厂对象中,我有一个$http.get()函数。谢谢!

2 个答案:

答案 0 :(得分:3)

如果您希望在完成所有请求后进行回调,则可以保存在数组中创建的所有承诺并与var allRequests = $q.all(arrayOfPromises)共同承诺

然后,您可以allRequests.then(callback)执行回调

答案 1 :(得分:1)

谢谢大家,我已经解决了这个问题:

 var promises = $scope.array.map(function (item) {
                        return factory.getX(item.id)
                            .success(function (_response) {

                            })
                            .error(function (_err) {
                                $scope.displayAlert(_err)
                            })
                    })

 $q.all(promises).then(function () {
        console.log("Solved all the promises")
    }
相关问题