【问题标题】:Angular chaining promises from foreach loop来自 foreach 循环的角链承诺
【发布时间】:2016-02-19 19:23:39
【问题描述】:

我有一组照片文件需要上传到 Azure 云存储,我使用 foreach 循环调用上传如下:

$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 返回 azure 存储路径,我需要将路径推送到 imagePathsArray

我如何使用 Angular Promise 来等待上传所有文件完成并且所有路径都存储在 imagePathsArray 中以便我可以继续

 $scope.data.Images = imagePathsArray ;

以便我可以获取数组中的路径并执行 $http post?

【问题讨论】:

    标签: angularjs azure angular-promise ng-file-upload


    【解决方案1】:

    您可以通过 $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】:

    在上传函数成功回调中,推送路径后:

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

    pushtoDatabase 内调用$http({ .... });

    注意:您可能需要考虑上传失败的可能性。在这种情况下,您可以使用失败文件的计数器来解决问题,例如 failCounter ,然后在 if 检查条件内

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      相关资源
      最近更新 更多