angularjs - promise never resolved in controller

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?


Solution 1:

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

Solution 2:

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)