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