Angular $q.when Demonstration
by taly2808
HTML
<div ng-app="myApp">{{status}}</div>
JavaScript
(function () {
var app = angular.module("myApp", []);
app.service('noPromise', function($timeout) {
return {
getResult: function() {
//return { status: "noPromise" };
return $timeout(function() {
return { status: "noPromise" };
}, 1000);
}
};
});
app.service("promise", ['$q', '$timeout', function($q, $timeout) {
return {
getResult: function() {
var deferral = $q.defer();
$timeout(function() {
deferral.resolve( { status: "promise" } );
}, 3000);
return deferral.promise;
}
};
}]);
app.run(['$rootScope', '$q', 'noPromise', 'promise',
function ($rootScope, $q, noPromise, promise) {
$rootScope.status = 'Ready.';
$q.when(noPromise.getResult()).then(function(result) {
$rootScope.status = result.status;
});
$q.when(promise.getResult()).then(function(result) {
$rootScope.status = result.status;
});
}]);
})();