I want to have a for loop that calls asynchronous functions for each iteration.
After the for loop, I want to execute another block of code, but not earlier than all the previous calls in the for loop have been resolved.
My problem at the moment is that either the code block after the for loop is executed before all asynchronous calls are finished OR it is not executed at all.
Part of the code with a FOR loop and a block of code after it (for full code, see fiddle ):
[..] function outerFunction($q, $scope) { var defer = $q.defer(); readSome($q,$scope).then(function() { var promise = writeSome($q, $scope.testArray[0]) for (var i=1; i < $scope.testArray.length; i++) { promise = promise.then( angular.bind(null, writeSome, $q, $scope.testArray[i]) ); } // this must not be called before all calls in for-loop have finished promise = promise.then(function() { return writeSome($q, "finish").then(function() { console.log("resolve"); // resolving here after everything has been done, yey! defer.resolve(); }); }); }); return defer.promise; }
I created a jsFiddle which can be found here http://jsfiddle.net/riemersebastian/B43u6/3/ .
At the moment, it looks like the execution order is in order (see console output).
I guess this is simply because every function call returns immediately without any real work. I tried deferring defer.resolve with setTimeout but failed (i.e. the last block of code never executed). You can see it in the broken block in the violin.
When I use real functions that write to and read from a file, the last block of code is executed until the last write operation is completed, which I donβt want.
Of course, the error may be in one of these read / write functions, but I would like to confirm that there is nothing wrong with the code that I posted here.
angularjs promise deferred angular-promise
SebastianRiemer Jan 09 '14 at 15:31 2014-01-09 15:31
source share