上传多个独立的附件CouchDB的使用angularjs [英] Uploading multiple standalone attachments to couchdb using angularjs

查看:310
本文介绍了上传多个独立的附件CouchDB的使用angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将多个文件上传到使用angularjs一个CouchDB文档。我试图此使用angular.forEach循环做,然而随着循环继续,而不等待previous循环来完成它的异步$ HTTP调用失败。
这是我的code如何看待当下:

I am trying to upload multiple files to a couchdb document using angularjs. I have attempted to do this using an angular.forEach loop, however this fails as the loop continues without waiting for the previous loop to finish its asynchronous $http calls. This is how my code looks at the moment:

angular.forEach($scope.fileList, function(value, key){
    couch.getRevisionId($scope.plan._id)
    .then(function(response){
        couch.uploadAttachment($scope.plan._id, response[1], value[0])
            .then(function(response2){
        console.log("Response2", response2);
        }, 
        function(reason2){
        console.log("Reason2", reason);
        });
    },
    function(reason){
        console.log("GetrevisionId failed reason=", reason)
   });
});

couch.getRevisionId是$ HTTP HEAD调用返回的附件保存到文档的当前版本ID的承诺。 couch.uploadAttachment是$ HTTP PUT调用其中保存附件的文件。这code适用于第一个文件,遗憾的是因为code异步运行循环的下一次运行首次运行已经把previous附件等couch.getRevisionId返回相同的版本ID为前previous通话,导致它试图将附件保存到一个更新的文档code失败,409的冲突。
是否有后续延迟循环,直到getRevisionId和uploadAttachment承诺已经返回后的一种方式?

couch.getRevisionId is an $http HEAD call returns a promise of the current revision id of the document the attachment is being saved to. couch.uploadAttachment is an $http PUT call which saves the attachment to the document. This code works for the first file, unfortunately as the code runs asynchronously the next run of the loop runs before the first has PUT the previous attachment and so couch.getRevisionId returns the same revision id as the previous call, causing the code to fail with a 409 conflict as it attempts to save the attachment to an updated document. Is there a way of delaying subsequent loops until after the getRevisionId and uploadAttachment promises have returned?

推荐答案

您可以链的承诺作为的问:关于序列文档,但使用的角度 $ q API

You could chain promises as described in the Q documentation about sequences, but using the Angular $q API

var asyncTask = function (value) {
    var deferred = $q.defer(); 
    ...
    return deferred.promise;
};

var list = [ ... ];

var deferred = $q.defer();
var promise = deferred.promise;
angular.forEach(list, function (value) {
    promise = promise.then(function () {
        return asyncTask(value);
    });
});
deferred.resolve();

看到一个完整的例子 rel=\"nofollow\">。

See a complete example here.

如果您的CouchDB的服务已经依赖于 $ Q ,那么你可能并不需要包装在另一个更高的层次 $ Q 的承诺。

If your CouchDB service already relies on $q then you might not need to wrap your async task inside another higher level $q promise.

这篇关于上传多个独立的附件CouchDB的使用angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆