AngularJS - 延迟递归承诺

时间:2014-06-06 15:34:50

标签: javascript angularjs q

我有一个调用异步函数(在循环中)的函数,它将为下一次函数调用提供参数。我认为编写代码会更有意义所以这就是我尝试过的(没有成功)。 我知道有很多关于这个问题的问题,但我真的尝试过我所看到的一切。

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

1 个答案:

答案 0 :(得分:0)

由于每个rev都需要新的removeAttachment(),因此无法使用$q.all(),您需要使用then()来确保异步调用排序,就像这样:

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