Skip to content

Instantly share code, notes, and snippets.

@Unitecho
Created May 6, 2013 11:26
Show Gist options
  • Save Unitecho/5524598 to your computer and use it in GitHub Desktop.
Save Unitecho/5524598 to your computer and use it in GitHub Desktop.
Angular - Promise $q
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
// since this fn executes async in a future turn of the event loop, we need to wrap
// our code into an $apply call so that the model changes are properly observed.
scope.$apply(function() {
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
});
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment