fbpx Skip to content

Aquent | DEV6

AngularJS – Promises

Written by: Alain Thibodeau

AngularJS comes with promise/deferred APIs that are simple to set up and are also built into the $http API. The Angular promise is basically a guarantee that some code will be fulfilled after other parts are done.

Single Promise:

myApp.controller('myController', ['$scope', '$q', function ($scope, $q) 
{var defer = $q.defer();
 
defer.promise.then(function () {
$scope.$emit('shoutEvent', {'message' : 'I kept my promise!'});
});
 
$scope.$on('someEvent', function (event, data) 
{defer.resolve();
});
}]);

In the above example we create a new instance of a deferred object which exposes a promise. Next, we access the promise and add the callback that we need. We can now resolve the promise when the ‘someEvent’ is received.

Multiple Promises:

myApp.controller('myController', ['$scope', '$q', function ($scope, $q) {
var defer1 = $q.defer(),
defer2 = $q.defer();
 
$scope.$on('someEvent', function (event, data) {
defer1.resolve();
});
$scope.$on('someOtherEvent', function (event, data) {
defer2.resolve();
});
 
$q.all([defer1.promise, defer2.promise]).then(function () {
$scope.$emit('shoutEvent', {'message' : 'I kept my promise to all of you'});
});
}]);

As shown above, when we need to wait for multiple promises to resolve and take action, we can use the $q.all() method to combine them into one promise.

These examples show how AngularJS promises are powerful. But, this post just touches a few of their features. There are other features you might be interested in such as chaining promises with return values, using them in templates and rejecting promises.

You can read more about them in the AngularJS documentation.

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details