在angularjs承诺链

时间:2016-06-15 13:38:33

标签: angularjs promise sharepoint-2013 angular-promise

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

因为如果我调用上传附件方法异步,我会收到409冲突错误。

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

请帮助我在for循环中链接承诺的最佳方法。

保存附件的常用方法:

 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方法。

我希望按顺序运行此循环,一旦循环完成,我需要处理所有承诺并向用户显示成功消息。

请帮我以有效的方式写下链接承诺。

2 个答案:

答案 0 :(得分: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)....

并按预期逐个执行

答案 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
 });
}