angular $q, How to chain multiple promises within and after a for-loop

What you need to use is $q.all which combines a number of promises into one which is only resolved when all the promises are resolved. In your case you could do something like: function outerFunction() { var defer = $q.defer(); var promises = []; function lastTask(){ writeSome(‘finish’).then( function(){ defer.resolve(); }); } angular.forEach( $scope.testArray, function(value){ promises.push(writeSome(value)); … Read more

Wait for all promises to resolve

I want the all to resolve when all the chains have been resolved. Sure, then just pass the promise of each chain into the all() instead of the initial promises: $q.all([one.promise, two.promise, three.promise]).then(function() { console.log(“ALL INITIAL PROMISES RESOLVED”); }); var onechain = one.promise.then(success).then(success), twochain = two.promise.then(success), threechain = three.promise.then(success).then(success).then(success); $q.all([onechain, twochain, threechain]).then(function() { console.log(“ALL PROMISES … Read more

How to use $http promise response outside success handler

But if I want to use $scope.tempObject after callback so how can I use it. ? You need to chain from the httpPromise. Save the httpPromise and return the value to the onFullfilled handler function. //save httpPromise for chaining var httpPromise = $http({ method: ‘GET’, url: ‘/myRestUrl’ }).then(function onFulfilledHandler(response) { $scope.tempObject = response console.log(“Temp Object … Read more

Caching a promise object in AngularJS service

Is this the right approach? Yes. The use of memoisation on functions that return promises a common technique to avoid the repeated execution of asynchronous (and usually expensive) tasks. The promise makes the caching easy because one does not need to distinguish between ongoing and finished operations, they’re both represented as (the same) promise for … Read more

Why are Callbacks from Promise `.then` Methods an Anti-Pattern

You should change it to var getTokens = function() { return $http.get(‘/api/tokens’); }; And, then in other module use yourModule.getTokens() .then(function(response) { // handle it }); As to why it’s an anti-pattern, I’d say that, first, it doesn’t allow you to further chain your success/fail handler methods. Second, it handles the control of processing the … Read more

AngularJS : Initialize service with asynchronous data

Have you had a look at $routeProvider.when(‘/path’,{ resolve:{…}? It can make the promise approach a bit cleaner: Expose a promise in your service: app.service(‘MyService’, function($http) { var myData = null; var promise = $http.get(‘data.json’).success(function (data) { myData = data; }); return { promise:promise, setData: function (data) { myData = data; }, doStuff: function () { … Read more