我是angularJS的新手,对承诺仍有一些困难......我有以下功能:
removeMultipleAttachments: function(docid, rev, attachmentIDs) {
var p = $q.when();
angular.forEach(attachments, function(file, index) {
return p.then(function (formerRes) {
return pouch.removeAttachment(docid, attachmentIDs[index], rev);
}).then(function(res) {
rev = res.rev;
$rootScope.$apply();
});
})
}
并且希望能够调用它并在完成时使用带有响应的.then(),例如:
removeMultipleAttachments(mydocID, myRev, myAttachments).then(function(responses){ ---is called only when done --- })
答案 0 :(得分:1)
执行$q.when()
会创建一个空的已解决的承诺
您尝试做的是连锁完成。您几乎就在那里,问题是您在[{1}}而不是链接中返回。
尝试:
forEach
请注意,这将按顺序执行 ,一次执行一个承诺。如果您想一次执行所有请求,可以使用removeMultipleAttachments: function(docid, rev, attachmentIDs) {
var p = $q.when();
var retvals = [];
angular.forEach(attachments, function(file, index) {
p = p.then(function (formerRes) { // NOTE THE ASSIGNMENT HERE
return pouch.removeAttachment(docid, attachmentIDs[index], rev);
}).then(function(res) {
retvals.push(res);
rev = res.rev;
$rootScope.$apply(); // You really don't need the apply here
});
})
return p.then(function(){ return retvals; }); // AND THE RETURN HERE
}
:
$q.all