In my controller I'm getting a promise from another service. I add a 'then' clause to it, but the 'then' is never called.
See this plunker: http://plnkr.co/edit/dX0Oz1?p=preview (javascript version)
'fakeLongRunningPromise' creates a promise that resolves itself after 2 seconds.
In the controller itself I send a note to the console once the promise is resolved.
I can tell that the promise is being resolved because "Resolving promise" it outputted to the console. Why doesn't it output "promise resolved"?
Thinking maybe the promise is going 'out of scope' because the controller returns?
$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.
$q is an Angular Service which facilitates running functions asynchronously. It's based on a library (Q) by Kris Kowal. $q. all() allows us to wait on an array (or object) of promises, $q. all() will combine these into a single promise.
Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
The AngularJS the result of promises resolution is propagated asynchronously, inside a $digest cycle. So, the callbacks registered with then
will be only called upon entering the $digest cycle. The setTimeout
executes "outside of the AngularJS world", and as such will not trigger callbacks.
The solution is to use Scope.$apply
or the $timeout
service. Here is the version with $apply:
window.setTimeout(function() {
console.log("Resolving promise");
$scope.$apply(function(){
deffered.resolve("worked");
});
}, 2000);
Here is a fixed plunk (JavaScript): http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=preview
I've used $timeout
instead of setTimeout
and it works:
# Resolve the promise after 2 seconds
$timeout( ()->
console.log "Resolving promise"
deffered.resolve ("worked")
, 2000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With