angularjs - 承诺从未在控制器中解决 [英] angularjs - promise never resolved in controller

查看:28
本文介绍了angularjs - 承诺从未在控制器中解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我收到了另一个服务的承诺.我给它添加了一个then"子句,但从来没有调用过then".

In my controller I'm getting a promise from another service. I add a 'then' clause to it, but the 'then' is never called.

看到这个 plunker:http://plnkr.co/edit/dX0Oz1?p=preview(javascript 版本)

See this plunker: http://plnkr.co/edit/dX0Oz1?p=preview (javascript version)

'fakeLongRunningPromise' 创建一个 2 秒后自行解决的承诺.

'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"?

认为 Promise 可能因为控制器返回而超出范围"?

Thinking maybe the promise is going 'out of scope' because the controller returns?

推荐答案

AngularJS 承诺解析的结果异步传播,在 $digest 循环内.因此,使用 then 注册的回调只会在进入 $digest 循环时被调用.setTimeout 在AngularJS 世界之外"执行,因此不会触发回调.

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.

解决方案是使用 Scope.$apply$timeout 服务.这是带有 $apply 的版本:

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);

这是一个固定的 plunk (JavaScript):http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=预览

Here is a fixed plunk (JavaScript): http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=preview

这篇关于angularjs - 承诺从未在控制器中解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆