首页 文章

在angularjs承诺链

提问于
浏览
1

我在SharePoint 2013中使用rest api上传附件,为此我需要在同步上调用上传附件方法 .

因为如果我调用上传附件方法异步我得到409冲突错误 .

如何在for循环中链接promise对象 . 我想在第一个附件成功中调用第二个附件方法,依此类推 .

请帮助我在for循环中链接promises的最佳方法 .

保存附件的常用方法:

var saveFileAngularJS = function (file, url) {
            var deferred = $q.defer();
            getFileBuffer(file).then(function (fileArrBuffer) {
                $http({
                    method: 'POST',
                    url: baseUrl + url,
                    headers: {
                        'Accept': 'application/json;odata=verbose',
                        'Content-Type': undefined,
                        'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
                    },
                    data: new Uint8Array(fileArrBuffer),
                    transformRequest: []                   
                }).then(function successCallback(data) {
                    deferred.resolve(data);
                    alert('Successfully saved.', data);
                }, function errorCallback(error) {
                    deferred.reject(error);
                    alert('Failed to save!!!.', error);
                });
            });
            return deferred.promise;
        };

方法调用:

for (var i = 0; i < $scope.files.length; i++) {
         var file = $scope.files[i]._file;
         var response = lssDealService.insertAttachment(transactionId, file);
}

 var insertAttachment = function (dealId, file) {
            var attachmentUrl = listEndPoint + "/GetByTitle('TransactionList')/GetItemById(" + dealId + ")/AttachmentFiles/add(FileName='" + file.name + "')";
            return baseService.saveFile(file, attachmentUrl);
        };

插入附件将调用SaveFile方法 .

我想按顺序运行这个循环,一旦循环完成,我需要处理所有的promises并向用户显示成功消息 .

请帮我有效地编写链接承诺 .

2 回答

  • 0

    让我们说你有附件作为一个数组,

    function uploadMyAttachements() {
        return myAttachements.reduce(function(promise, attachment) {
            return promise.then(function () {
                return upload(attachment);
            })
            .then(function(result) {
                console.log('RESULT FOR LAST UPLOAD', result);
            });
        }, Promise.resolve());
    }
    
    function upload(attachment) {
        //upload the attachment to sharepoint
        //and return a promise here
    }
    
    uploadMyAttachements().catch(function(err) {
        //if anything in the promise chain fails
        //it stops then and there and CATCHED here
    });
    

    现在发生了什么,使用Array.reduce,我们创建了一系列承诺,如下所示

    upload(0).then(handleResult_0).upload(1).then(handleResult_1)....
    

    并按预期逐个执行

  • 0

    投掷我的2便士:

    $scope.attachments = []; //modified via binding.
    
    function uploadAttachments(){
     //Reduce the files array into a promise array with the uploadOne method
     //then return the promise when every promise has been resolved or one has rejected.
     return $q.all($scope.attachments.reduce(uploadOne, []));
    }
    
    function uploadOne(file){
     //Upload one, return promise. Use $http or $resource.
    }
    
    //Note - a more advanced way of doing this would be to send the files as batch (one
    //$http post) as FormData. There are some good wrappers for angular.
    
    $scope.upload = function(){
     uploadAttachments().then(function(results){
      //Array of results
     }).catch(function(e){
      //Error handler
     });
    }
    

相关问题