简体   繁体   中英

AngularJS - Deferred recursive promises

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;
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM