Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs - promise never resolved in controller

Tags:

angularjs

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?

like image 529
Roy Truelove Avatar asked Jan 09 '13 21:01

Roy Truelove


People also ask

Why we use$ q in AngularJS?

$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.

What is$ q Angular?

$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.

Why do we use promises in angular?

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.


2 Answers

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

like image 174
pkozlowski.opensource Avatar answered Oct 18 '22 17:10

pkozlowski.opensource


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)
like image 2
asgoth Avatar answered Oct 18 '22 16:10

asgoth