在$ js中解决非$ q承诺后自动应用$ scope更改(触发摘要) [英] Automatically apply $scope changes (trigger digest) after a non-$q promise resolves in angularjs

查看:57
本文介绍了在$ js中解决非$ q承诺后自动应用$ scope更改(触发摘要)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您拥有:

function myPromise() {
  // using some promise lib other than $q, like Q or bluebird
  var defer = Q.defer();
  defer.resolve('John');
  return defer.promise;
}

然后您会看到类似的内容

and then you have something like:

function foo() {
  return myPromise().then(function (name) {
    return name + ' Smith';
  });
}

foo().then(function (name) {
  $scope.$apply(function () { // or can use $timeout
    console.log('after foo');
    $scope.text = 'Hey ' + name;
  });
});

有没有一种方法可以修改foo,以便将 foo块之后的自动包装在$ scope.$ apply()中?即我们可以拥有:

Is there a way to modify foo so that the after foo block is automatically wrapped in $scope.$apply()? i.e. we can then just have:

foo().then(function (name) {
  console.log('after foo');
  $scope.text = 'Hey ' + name;
  // $scope.$apply() is automatically called after this block is executed
});

我问的原因是我正在开发一个API,用户将在其中进行几个此类foo调用,如果在foo promise解决后自动触发了摘要循环,它将大大减少用户代码.我知道我可以使用回调来完成此操作,但我希望有一种更干净的方法仅使用promise.

The reason I ask is that I am developing an API where the user will make several of these foo calls and it would greatly cut down on the user's code if the digest cycle was automatically triggered after the foo promise resolves. I know I can use a callback to accomplish this, but I'm hoping there is a cleaner way that just uses promises.

我的直觉是解决方案在于将非$ q承诺包装在$ q承诺中...

My hunch is that the solution lies in wrapping the non-$q promise in a $q promise...

推荐答案

我仅通过将我的API函数包装在$ timeout块中即可触发摘要周期,例如

I was able to trigger the digest cycle just by wrapping my API functions in $timeout blocks, e.g.

function foo() {
  return $timeout(function () {
    return myPromise().then(function (name) {
      return name + ' Smith';
    });
  });
}

这篇关于在$ js中解决非$ q承诺后自动应用$ scope更改(触发摘要)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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