我如何使用与蓝鸟角? [英] How do I use Bluebird with Angular?
问题描述
我试着用角与蓝鸟承诺:
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用
并没有更新。除非我增加了一个手动 $范围。$适用
我宁愿避免的。
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)
我使用蓝鸟2.0,我得到了 href=\"https://rawgit.com/petkaantonov/bluebird/2.0/js/browser/bluebird.js\">。
I'm using Bluebird 2.0 which I got here.
推荐答案
好吧,如果我们看一下角自己的诺言是如何工作的,我们需要让蓝鸟到 $ 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.
如果我们这样做,其实两者的实现是承诺/ A + 的投诉意味着我们可以$ Q code和蓝鸟之间$互操作C $ç意义,我们可以使用所有的蓝鸟的特征角code自如。
If we do that, the fact both implementations are Promises/A+ complaint means we can interop between $q code and Bluebird code meaning we can use all of Bluebird's features in Angular code freely.
蓝鸟公开此功能,其<一个href=\"https://github.com/petkaantonov/bluebird/blob/master/API.md#promisesetschedulerfunction-scheduler---void\"><$c$c>Promise.setScheduler$c$c>功能:
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应用= ...
行之后,一切都会正常工作。对于加分,把青鸟的服务,让你可以注入它,而不是使用它的全局命名空间。
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.
下面是一个[ 小提琴 ]说明此行为。
Here is a [Fiddle] illustrating this behavior.
请注意,除了所有功能蓝鸟拥有超过 $ Q
,更重要的问题之一是,青鸟会的不的运行 $ exceptionHandler的
,而是会自动跟踪未处理的拒绝,这样你就可以扔
自由地与蓝鸟的承诺和蓝鸟将数字出来。此外调用 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.
这篇关于我如何使用与蓝鸟角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!