var app = angular.module('app', []); app.controller('ctrl', ['$scope', '$timeout', '$q', function($scope, $timeout, $q) { var results = [{ id: 1, name: 'one' }, { id: 2, name: 'two' }, { id: 3, name: 'three' }]; var promisesFunction = function() { var uploadPromises = [], printforms = [], printPromises = [], printDefer = [], counter = 0, defer = $q.defer(); angular.forEach(results, function(temp, key) { // first delay $timeout(function() { var html = '<div><span>My Name Is Jack</span></div>'; var data = { sFunnyName: 'fluffy.html', sContent: '<p>some content</p>' }; printDefer[key] = $q.defer(); printforms[key] = { html: html, data: data }; printPromises[key] = printDefer[key].promise; defer.resolve(); }); uploadPromises.push(defer.promise); }); var asyncUpload = function(i, print, defs) { if (i < print.length) { // emulation of $http.post console.log('Start upload ' + i); $timeout(function() { results[i].value = 'done'; printDefer[i].resolve(); console.log(results[i].value + ' ' + i); ++i; asyncUpload(i, print, defs); }, 1000); } }; // this $q.all wait until first delay is done for all 3 elemets. // Then upload this items. var first = $q.all(uploadPromises).then(function() { console.log('First promise is done!'); asyncUpload(counter, printforms, printDefer); }); // this $q.all wait until all items is loaded. $q.all([first, printPromises]).then(function(uploadResults) { console.log('RESOLVED!') }); } promisesFunction(); } ]) <!DOCTYPE html> <html ng-app="app"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Example</title> </head> <body ng-controller='ctrl'> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> </body> </html> I have an array of objects. I want to load them all and then return all the results together, in a single ensemble. But in my function there are 2 delays, in connection with this I decided to use promises:
$timeout(I need it to wait for$compilecompile content from my objects, but that's not the point), 2$http.post(when I already compiled the content with the objects passed to the server).
Therefore, I use $q.all to wait for all these actions to be carried out. In debbager, I see that some promises with status still 0, but already $q.all missed them. Tell me where I was wrong?
An example of jsbin that completely simulates the situation.