Created
May 6, 2013 11:26
-
-
Save Unitecho/5524598 to your computer and use it in GitHub Desktop.
Angular - Promise $q
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 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