I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are generated by $resource objects within each iteration, which leads me to believe that the asynchronous filling of the promises array is causing the problem.
My observation is that the promise array returned by the $q.all() method is always empty. It appears that $q.all() does not wait for the array to be populated. However, I cannot be certain if this is indeed the root cause of the issue.
If it is not possible to achieve my goal with $q.all(), I would greatly appreciate any guidance on alternative methods to execute code once all promises have been resolved.
Below is the code snippet I am currently working with:
var promisesArray = [];
var images, postObject;
files.readFile('images.txt')
.then(function (data) {
images= angular.fromJson(data);
images.forEach(function (image, idx) {
var deferred = $q.defer();
if (!image.sent) {
files.readFile(image.name)
.then(function (data) {
postObject = angular.fromJson(data);
$resource(EndPointsService.baseURL + "images").save(postObject, function(data) {
deferred.resolve(data);
if (data.status) {
image.sent= true;
}
},function(error){
console.log(error);
});
promisesArray.push(deferred.promise);
},function(error){
console.log(error);
});
}
});
$q.all(promisesArray).then(function (data) {
console.log(data);
files.writeFile("images.txt", images)
.then(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
});
},function(error){
console.log(error)
});