在AngularJS中的最后一次ajax调用之后打印消息

时间:2017-05-05 09:08:01

标签: angularjs ajax

我正在尝试在循环中进行少量ajax调用。我想在我上一次ajax成功时打印一条消息。我在这里做错了什么建议。

        $scope.defer = $q.defer();
        $scope.promises = [];
        $scope.array = [1,2,3,4,5,6,7,8,9,10];
        $scope.makecall = function(){
            angular.forEach($scope.array, function(index){
                $timeout(function() {
                   var promise = $http({
                        url   : 'https://jsonplaceholder.typicode.com',
                        method: 'GET',
                    }).
                    success(function(data){
                    });

                    $scope.promises.push(promise);
                }, index * 2000);
            });
            return $scope.defer.promise;
        }
        $scope.makecall();
        $q.all($scope.promises).then(function(){
            console.log('over!');
        });

1 个答案:

答案 0 :(得分:1)

我认为你可以查看SO

Wait for all promises to resolve

$q.all([one.promise, two.promise, three.promise]).then(function() {
    console.log("ALL INITIAL PROMISES RESOLVED");
});

var onechain   = one.promise.then(success).then(success),
    twochain   = two.promise.then(success),
    threechain = three.promise.then(success).then(success).then(success);

$q.all([onechain, twochain, threechain]).then(function() {
    console.log("ALL PROMISES RESOLVED");
});

您也可以查看

function outerFunction(){

var defer = $q.defer();
var promises = [];

function lastTask(){
    writeSome('finish').then( function(){
        defer.resolve();
    });
}

angular.forEach( $scope.testArray, function(value){
    promises.push(writeSome(value));
});

$q.all(promises).then(lastTask);

return defer.promise;

}