2014-06-06 165 views
0

我有一个函数调用一个异步函数(在一个循环中),它将为我提供一个函数下一次调用的参数。我认为编写代码会更有意义,所以这是我试过的(没有成功)。 我知道很多问题已经被问及这个问题,但我真的尝试了我所看到的一切。AngularJS - 延期递归承诺

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

我首先看到的是 var p = $ q.when(); 应该是 var p = $ q.defer(); – DrDyne

+0

您是否需要依次删除附件,或者您不关心订单? –

+0

好的,但是当()不应该用在承诺中? – ncohen

回答

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

谢谢你,它解决了我的大部分问题,但是当所有的承诺完成后,哪里可以添加一个函数或console.log('DONE')? – ncohen

+0

哦,我也需要赶上最后的回应...我应该怎么做才能够调用这个函数如下:removeMultipleAttachments(docid,rev,attachmentIDs).then(function(response){... catch this here ...}) – ncohen

+0

@ncohen我更新了我的答案,看看。 –