callback after async forEach AngularJS

后端 未结 4 496
一生所求
一生所求 2020-12-07 21:24

How do I add a callback function after an async forEach Loop?

Here is some better context:

$scope.getAlbums = function(user, callback) {
            


        
4条回答
  •  再見小時候
    2020-12-07 21:51

    $scope.getAlbums = function(user, callback) {
    
            var promiseArr = [];
            $scope.albumsList.forEach(function (obj, i) {
                var anHttpPromise = 
                $scope.getAlbum(user, obj.id, function(value){
                    $scope.albums.push(value);
                });
                promiseArr.push(anHttpPromise);
            });
    
            $q.all(promiseArr).then(function(){
                // This callback function will be called when all the promises are resolved.    (when all the albums are retrived)      
            })
        };
    
        $scope.getAlbum = function(user, id, callback) {
            var anHttpPromise = Imgur.album.get({user:user, id:id},    
                function(value) {
                    return callback(value.data);
                }
            );
            return anHttpPromise;
        }
    

    In the above code:

    1. The getAlbum is made to return an promise.
    2. Collecting an promise for each iteration of the getAlbums list
    3. Once all the promises are collected, the promise array is passed to $q.all
    4. The $q.all method instead returns an final promise whose callback function will be triggered once all the promises in the array are resolved.

提交回复
热议问题