Understanding and implementing a basic promise
Promises are absolutely essential to many of the core aspects of AngularJS. When learning about promises for the first time, the formal terms can be an impediment to their complete understanding as their literal definitions convey very little about how the actual promise components act.
How to do it…
A promise implementation in one of its simplest forms is as follows:
// create deferred object through $q api
var deferred = $q.defer();
// deferred objects are created with a promise attached
var promise = deferred.promise;
// define handlers to execute once promise state becomes definite
promise.then(function success(data) {
// deferred.resolve() handler
// in this implementation, data === 'resolved'
}, function error(data) {
// deferred.reject() handler
// in this implementation, data === 'rejected'
});
// this function can be called anywhere to resolve the promise
function asyncResolve() {
deferred.resolve('resolved');
};
// this...