Angularjs $q.all Example - Jquery
What is $q promises in angularjs?
Snippet Code
Angularjs promise is used to view the the built-in $q service. $q.all is a service which helps you to run function asynchronously and use their return value after they processed. The sample code using $q promises in angularjs is given below.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>
<script>
function PromiseCtrl($scope, $q, $timeout) {
var getPromise = function(delay) {
var deferred = $q.defer();
$timeout(function() {
if(delay > 0) {
deferred.resolve("Success");
} else {
deferred.reject("Fail");
}
}, delay);
return deferred.promise;
};
$scope.result = "Waiting";
$q.all([
getPromise(1000),
getPromise(2000),
getPromise(3000)
]).then(function(value) {
$scope.result = value;
}, function(reason) {
$scope.result = reason;
});
}
</script>
<div ng-app>
<div ng-controller="PromiseCtrl">
{{result}}
</div>
</div>
Tags