0

I have a function that calls an asynchronous function (in a loop) that will provide me a parameter for the next call of the function. I think writing the code will make more sense so here is what I tried (with no success). I know many questions have been asked about this subject but I really tried everything I saw.

    removeMultipleAttachments: function(docid, rev, attachmentIDs) {
        var requests = [];
        var deferred = $q.defer();
        var p = $q.when();
        console.log(attachmentIDs);
        angular.forEach(attachmentIDs, function(file, index) {
            p = p.then(function (formerRes) {

                return pouch.removeAttachment(docid, attachmentIDs[index].name, rev, function (err, res) {
                    $rootScope.$apply(function () {
                        if (err) {
                            deferred.reject(err);
                        } else {
                            rev = res.rev;
                            console.log(rev);
                            deferred.resolve(res);
                        }
                    })
                });
            });
            requests.push(p);
        })
        $q.all(requests).then(function(){
            console.log('DONE');
        });

        return deferred.promise;
    }
Nate
  • 7,606
  • 23
  • 72
  • 124

1 Answers1

0

Since you need a new rev for each removeAttachment(), you can't use $q.all(), you need to ensure the async call ordering by using then(), like this:

removeMultipleAttachments: function(docid, rev, attachmentIDs) {
    console.log(attachmentIDs);
    var p = $q.when();
    angular.forEach(attachmentIDs, function(file, index) {
        p = p.then(function (formerRes) {
            var deferred = $q.defer();

            pouch.removeAttachment(docid, attachmentIDs[index].name, rev, function (err, res) {
                if (err) {
                    deferred.reject(err);
                } else {
                    rev = res.rev;
                    console.log(rev);
                    deferred.resolve(res);
                }
                $rootScope.$apply();
            });

            return deferred.promise;
        });

    return p.then(function(res) {
        console.log('DONE');
        return res;
    });
}
Ye Liu
  • 8,946
  • 1
  • 38
  • 34
  • Thanks Ye, it solves most of my problems but where can add a function or console.log('DONE') when all the promises have been done? – Nate Jun 07 '14 at 18:43
  • Oh and I also need to catch the last response... what should I do to be able to call this function as follow: removeMultipleAttachments(docid, rev, attachmentIDs).then(function(response){ ... catch response here ...}) – Nate Jun 08 '14 at 12:41