Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...