AngularJS Promises - $q.all()
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">Let's use promises in AngularJS to do asynchronous calculations.
<br>2 x 100 = {{myValue}}
<br>3 x 100 = {{myValue2}}
<br>{{finishedMessage}}</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
// This function will return the argument multiplied
// by 100 after waiting for a period of time up to two
// seconds. This is to demonstrate an asychronous activity.
function getValue(num) {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve(num * 100);
}, Math.random() * 2000);
// Return the promise to allow other code to act
// on the result.
return deferred.promise;
}
// Let's get a promise for calculating the value of
// 2 x 100.
var getMyValue = getValue(2);
// Once the code is finished calculating, specify
// a function to execute with the returned value
getMyValue.then(function (val) {
$scope.myValue = val;
});
// Let's also log the result of the calculation to console.
getMyValue.then(function (val) {
console.log("The result of the calculation was " + val + ".");
});
// At the same time, let's get a promise for calculating
// the value of 3 x 100.
var getMyValue2 = getValue(3);
// The following function will take the result of the
// calculation and post it to the page.
getMyValue2.then(function (val) {
$scope.myValue2 = val;
});
// Now, once both calculations have been completed, we want
// to post a message to the page indicating that's the case.
// The following line generates a promise that is fulfilled
// once the two existing promises we've made are fulfilled.
var finished = $q.all([getMyValue, getMyValue2]);
// The following function will post the finished message to
// the page after the promise is fulfilled.
finished.then(function () {
$scope.finishedMessage = "All calculations are complete!";
});
}