Promises in AngularJS
Promises
Promises(約束) are objects which were proposed by ECMAScript 6. Their purpose is to run asynchronous operations. For example, if the part of a code needs a certain resource, it could load it in a promise, and resume the execution of this part of the code once the loading has completed. A promise can have three states:
- Pending: The promise is still executing.
- Fulfilled: The promise has successfully completed.
- Rejected: The promise has completed with an error.
Implementation: The $q service
In AngularJS, promises are created using a service named $q. It is based on Q, an independant JavaScript library.
Example
Let's say we have a resource which takes some time to load. Instead of waiting for the loading to finish, we're going to load it asynchronously and only display it when it is available.
JSFiddle: http://jsfiddle.net/Maerig/4kg4ht29/
Create the promise
function createLoadPromise() {
var deferred = $q.defer();
// Timeout to simulate the loading
$timeout(function() {
var resource = "Resource content";
if(resource != null) {
// Fulfilled: The promise has successfully completed.
deferred.resolve(resource);
}
else {
// Rejected: The promise has completed with errors.
deferred.reject("An error occured while loading the resource.")
}
}, 1000);
return deferred.promise;
}
Use the promise
$scope.loadResource = function() {
$scope.resource = "Loading..."
var promise = createLoadPromise();
promise.then(function(resource) {
$scope.resource = resource;
}, function(error) {
$scope.resource = "";
alert(error);
});
}