angularjs - foreach 循环的 Angular 链接 promise

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

我有一组照片文件需要上传到 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?

最佳答案

您可以使用 $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);
    })
};

关于angularjs - foreach 循环的 Angular 链接 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33773610/

相关文章:

javascript - 我对 Angular 状态 promise 解决有什么误解?

javascript - onLoadFinished 触发时页面未完全加载/渲染

angularjs - 在保存实体 PrimaryGeneratedColumn 值时未生成,给出 NOT NULL 约束错误

azure - 创建 Azure 逻辑应用接收的 Azure 存储帐户事件订阅时出现问题

ssl - 带有 pfx 文件的 Azure https

服务主体的 Azure Databricks Git 凭据

javascript - Angularjs:这是使用指令的正确位置吗?

javascript - Angular ,element.bind 特定的 div

javascript - 在 Angular JS 中第一次拒绝 promise 时停止/退出循环

javascript - Promise 决议传递的是 Promise 而不是值(value)