如何在 Angular 中使用 Bluebird? [英] How do I use Bluebird with Angular?
问题描述
我尝试将 Angular 与 Bluebird 承诺一起使用:
I tried using Angular with Bluebird promises:
HTML:
<body ng-app="HelloApp">
<div ng-controller="HomeController">{{name}} {{also}}</div>
</body>
JS:
// javascript
var app = angular.module('HelloApp', []);
app.controller("HomeController", function ($scope) {
var p = Promise.delay(1000).then(function () {
$scope.name = "Bluebird!";
console.log("Here!", $scope.name);
}).then(function () {
$scope.also = "Promises";
});
$scope.name = "$q";
$scope.also = "promises";
});
window.app = app;
[小提琴]
然而,无论我尝试什么,它一直保持"$q promises"
并且没有更新.除非我添加了一个我宁愿避免的手动 $scope.$apply
.
However, no matter what I tried, it kept staying "$q promises"
and did not update. Except if I added a manual $scope.$apply
which I'd rather avoid.
(我知道这是可能的,因为 $q 做到了)
(I know it's possible since $q does it)
我正在使用 Bluebird 2.0,我在这里.
I'm using Bluebird 2.0 which I got here.
推荐答案
这是可能的,甚至很容易!
好吧,如果我们看看 Angular 自己的 promises 是如何工作的,我们需要让 Bluebird 到 $evalAsync
某处以获得完全相同的行为.
This is possible, and even quite easy!
Well, if we look at how Angular's own promises work, we need to get Bluebird to $evalAsync
somewhere in order to get the exact same behavior.
如果我们这样做,事实上两个实现都Promises/A+ 兼容意味着我们可以在 $q
代码和 Bluebird 代码,意味着我们可以在 Angular 代码中自由使用 Bluebird 的所有功能.
If we do that, the fact both implementations are Promises/A+ compliant means we can interop between $q
code and Bluebird code, meaning we can use all of Bluebird's features in Angular code freely.
Bluebird 公开了此功能,其<代码>Promise.setScheduler 功能:
Bluebird exposes this functionality, with its Promise.setScheduler
functionality:
// after this, all promises will cause digests like $q promises.
function trackDigests(app) {
app.run(["$rootScope",function ($rootScope) {
Promise.setScheduler(function (cb) {
$rootScope.$evalAsync(cb);
});
}]);
}
现在我们要做的就是添加一个:
Now all we have to do is add a:
trackDigests(app);
var app = ...
行之后的
行,一切都会按预期进行.为了获得奖励,请将 Bluebird 放入服务中,以便您可以注入它,而不是在全局命名空间中使用它.
line after the var app = ...
line, and everything will work as expected. For bonus points, put Bluebird in a service so you can inject it rather than use it on the global namespace.
这是说明这种行为的 [Fiddle].
Here is a [Fiddle] illustrating this behavior.
请注意,除了 Bluebird 在 $q
上的所有功能外,更重要的一个是 Bluebird 不会运行 $exceptionHandler
,而是会自动跟踪未处理的拒绝,因此您可以使用 Bluebird 承诺自由地throw
,Bluebird 会找出它们.此外,调用 Promise.longStackTraces()
可以帮助调试很多.
Note that besides all the features Bluebird has over $q
, one of the more important ones is that Bluebird will not run $exceptionHandler
, but instead will automatically track unhandled rejections, so you can throw
freely with Bluebird promises and Bluebird will figure them out. Moreover calling Promise.longStackTraces()
can help with debugging a lot.
这篇关于如何在 Angular 中使用 Bluebird?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!