Angular chaining promises from foreach loop

流过昼夜 提交于 2019-12-20 04:38:52

问题


I have an array of photo files that needed to upload to Azure Cloud Storage, and i using foreach loop to call upload as below:

$scope.savetemplate = function () { 
     var imagePathsArray = [];

     $scope.filesimage = [];
     $scope.filesimage.push($scope.file1);
     $scope.filesimage.push($scope.file2);
     $scope.filesimage.push($scope.file3);


    for (var i in $scope.filesimage) {
        $scope.upload($scope.filesimage[i]);
    }


    $scope.data.Images = imagePathsArray ;

     $http({
              //after finish uploads i need to post the paths 
              //of all images to save into database
     })
 };


$scope.upload = function (file) {
  Upload.upload({
       url: '/uploadImage',
       data: { file: file }
    }).then(function (resp) {
       imagePathsArray.push(resp.data);

    })
};

resp.data returns azure storage path and i need to push the paths into the imagePathsArray

How can i uses Angular Promise to wait for upload all the files finished and all the paths are stored in the imagePathsArray so i can proceed with

 $scope.data.Images = imagePathsArray ;

so that i can get the paths in the array and perform $http post?


回答1:


You can do that with $q.all.

var promises = [];
for (var i in $scope.filesimage) {
    promises.push(upload($scope.filesimage[i]));
}
$q.all(promises).then(function() {
    $scope.data.Images = imagePathsArray ;

    $http.post({
          //after finish uploads i need to post the paths 
          //of all images to save into database
    });
});

function upload(file) {
    return Upload.upload({
       url: '/uploadImage',
       data: { file: file }
    }).then(function (resp) {
       imagePathsArray.push(resp.data);
    })
};



回答2:


In the success callback of the upload function, after pushing the path:

imagePathsArray.push(resp.data);
if(imagePathsArray.length == $scope.filesimage.length){
  pushtoDatabase();
}

Inside pushtoDatabase call the $http({ .... });

NOTE : You might like to consider the probability of the upload getting failed. In that case you can work-around using a counter of failed files say failCounter , and then inside the if check for the condition

if ((imagePathsArray.length + failCounter) == $scope.filesimage.length){....}



来源:https://stackoverflow.com/questions/33773610/angular-chaining-promises-from-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!