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

查看:14
本文介绍了在 angularjs 中解决非 $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;
}

然后你有类似的东西:

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 以便 after 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.

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

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

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