<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-controller="MyCtrl">
Hello there!
<br>
<br>Please check the console.log to see the order of printed out text ...
<br>
<br> Question 1: Is this the correct way of chaining async calls?
<br> Question 2: Is the resulting order of outputs in the console random or is it guaranteed that the last block will always be executed last?
<br> Question 3: How can I, for simulation purposes, delay the defer.resolve() within the writeSome function for the FOR-loop calls, so I can be sure the calls are really chained correctly and the result is not randomly correct?
</div>
JavaScript
var myApp = angular.module('myApp',[]);
// in real case, this is writing to a file which I want to wait for
function writeSome($q, text) {
var defer = $q.defer();
console.log("writeSome: " + text);
defer.resolve();
// Delaying the resolve here does not work, why? No further code is executed if I try it like that.
//setTimeout(function() { defer.resolve()}, 1000);
return defer.promise;
};
// in real case, this is reading some JSON from file which I want to wait for
function readSome($q, $scope) {
var defer = $q.defer();
console.log("readSome ...");
defer.resolve();
return defer.promise;
}
// this is the function called from the template
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;
}
function MyCtrl($scope, $q) {
// prepare some data for testing
$scope.testArray = [];
$scope.testArray.push(1);
$scope.testArray.push(2);
$scope.testArray.push(3);
outerFunction($q, $scope).then(function() {
// in real case, some reloading is done here which depends on
// all save operations being done BEFORE reloading
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.