gpt4 book ai didi

javascript - AngularJS 创建延迟函数

转载 作者:行者123 更新时间:2023-11-30 05:35:20 25 4
gpt4 key购买 nike

我是 angularJS 的新手,在 promise 方面仍然有一些困难......我有以下功能:

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

最佳答案

执行 $q.when() 创建一个空的 resolved promise

您要做的是链完成。你快到了,问题是你在 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
}

请注意,这将顺序执行,一次一个 promise 。如果你想一次执行所有的请求,你可以使用$q.all:

removeMultipleAttachments: function(docid, rev, attachmentIDs) {
var p = $q.when();
return $q.all(attachments.map(function(file,index){
// not sure what to do with the res.rev = rev part
return pouch.removeAttachment(docid,attachmentIDs[index], rev);
});
}

关于javascript - AngularJS 创建延迟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com