What's promise
Angular’s event system provides a lot of power to our Angular apps. One of the most powerful features that it enables is automatic resolution of promises.
Promises are a method of resolving a value or not in an asynchronous manner. Promises are objects that represent the return value or a thrown exception that a function may eventually provide.
Promises are incredibly useful in dealing with remote objects and we can think of them as a proxy for them.
- Only one resolve or reject will ever be called
- – resolve will be called with a single fulfillment value
- – reject will only be called with a single rejection reason
- If the promise has been resolved or rejected, any handlers depending upon them will still be called
- Handlers will always be called asynchronously
Promise in AngularJS
Angular’s event-loop gives angular the unique ability to resolve promises in it’s $rootScope. $evalAsync stage (see under the hood for more detail on the run loop). The promises will sit inert until the $digest run loop finishes.
bind promise and view directly
This allows for Angular to turn the results of a promise into the view without any extra work. It enables us to assign the result of an XHR call directly to a property on a $scope object and think nothing of it. For instance, we might have a list of friends in a view, like so:
<
li ng-repeat=
"friend in friends">
{{ friend.
name }}
</
li>
</
ul>
'myApp', [])
.controller(
'DashboardController', [
'$scope',
'UserService',
function($scope, UserService) {
// UserService's getFriends() method
// returns a promise
$scope.friends
= User.getFriends(
);
}]);
How to create a promise
In order to create a promise in Angular, we’ll use the built-in $q service. The $q service provides a few methods in it’s deferred API.
1. inject $q service
First, we’ll need to inject the $q service into our object where we want to use it.
'myApp', [])
.factory(
'UserService', [
'$q',
function($q) {
// Now we have access to the $q library
}]);
2. $q.defer()
= $q.defer();
three methods and the
single promise property that can be used in dealing with the promise.
resolve(value)
.resolve({name
:
"Ari", username
:
"@auser"});
reject(reason)
.reject(
"Can't update user");
// Equivalent to
deferred.resolve(
$q.reject(
"Can't update user"));
notify(value)
promise property
'UserService', [
'$q',
function($q) {
var getFriends
=
function(id) {
var deferred
=
$q.defer();
// Get friends from a remote server
$http.get(
'/user/'
+ id
+
'/friends')
.success(
function(data) {
deferred.resolve(data.friends);
})
.error(
function(reason) {
deferred.reject(reason);
});
return
deferred.promise;
}
}]);
3. interact with promise
then(successFn, errFn, notifyFn)
successFn or the
errFn asynchronously as soon as the result is available. The callbacks are always called with a single argument: the result or the rejection reason.
notifyFn callback may be called zero or more times to provide a progress status indication before the promise is resolved or rejected.
The then() method always returns a new promise which is either resolved or rejected through the return value of the successFn or the errFn. It also notifies through the notifyFn.
catch(errFn)
.catch(function(reason){}):
'/user/'
+ id
+
'/friends')
.
catch(
function(reason) {
deferred.reject(reason);
});
finally(callback)
'finally'](
function() {});
- These promise chains are how Angular can support $http’s interceptors.
- $q is integrated with the angular $rootScope model, so resolutions and rejections happen quickly inside the angular
- $q promises are integrated with angular’s templating engine which means that any promises that are found in the views will be resolved/rejected in the view
- $q is tiny and doesn’t contain the full functionality of the Q library
$q library
all(promises)
combine into a single promise, then we can use the $q.all(promises) method to combine them all into a single promise. This method takes a single argument:
defer()
reject(reason)
This will create a promise that is resolved as rejected with a specific reason. This is specifically designed to give us access to forwarding rejection in a chain of promises.
This is akin to throw in javascript. In the same sense that we can catch an exception in javascript and we can forward the rejection, we’ll need to rethrow the error. We can do this with $q.reject(reason).
This method takes a single parameter:
when(value)
This allows for us to deal with an object that may or may not be a promise.