Created
May 5, 2016 10:57
-
-
Save AlphaNerd/58ab2e8ae9ed86b50f52af7ad0476604 to your computer and use it in GitHub Desktop.
AngularJS promises in a nut shell. $q boilerplate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://jsfiddle.net/alphanerds/46x3f21d/1/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function TodoCtrl($scope, $q, $timeout) { | |
function createPromise(name, timeout, willSucceed) { | |
$scope[name] = 'Running'; | |
var deferred = $q.defer(); | |
$timeout(function() { | |
if (willSucceed) { | |
$scope[name] = 'Completed'; | |
deferred.resolve(name); | |
} else { | |
$scope[name] = 'Failed'; | |
deferred.reject(name); | |
} | |
}, timeout * 1000); | |
return deferred.promise; | |
} | |
// Create 5 promises | |
var promises = []; | |
var names = []; | |
for (var i = 1; i <= 5; i++) { | |
var willSucceed = true; | |
if (i == 2) willSucceed = false; | |
promises.push(createPromise('Promise' + i, i, willSucceed)); | |
} | |
// Wait for all promises | |
$scope.Status1 = 'Waiting'; | |
$scope.Status2 = 'Waiting'; | |
$q.all(promises).then( | |
function() { | |
$scope.Status1 = 'Done'; | |
}, | |
function() { | |
$scope.Status1 = 'Failed'; | |
} | |
).finally(function() { | |
$scope.Status2 = 'Done waiting'; | |
}); | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div ng-app> | |
<h2>Example showing $q usage. Basic promise setup</h2> | |
<br/> | |
<div ng-controller="TodoCtrl"> | |
<div ng-bind="'Promise1: ' + Promise1"></div> | |
<div ng-bind="'Promise2: ' + Promise2"></div> | |
<div ng-bind="'Promise3: ' + Promise3"></div> | |
<div ng-bind="'Promise4: ' + Promise4"></div> | |
<div ng-bind="'Promise5: ' + Promise5"></div><br /> | |
<div ng-bind="'Status1: ' + Status1"></div> | |
<div ng-bind="'Status2: ' + Status2"></div> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment