我尝试将Angular与Bluebird Promise一起使用:
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,否则我会避免使用。
"$q promises"
$scope.$apply
(我知道这是可能的,因为$ q可以这样做)
我正在使用Bluebird2.0,我在这里。
好吧,如果我们看看Angular自己的诺言,我们需要将Bluebird带到$evalAsync某个地方才能获得完全相同的行为。
$evalAsync
如果这样做,那么两个实现都符合Promises /A+的事实意味着我们可以在$q代码和Bluebird代码之间进行互操作,这意味着我们可以在Angular代码中自由使用Bluebird的所有功能。
$q
蓝鸟通过以下功能公开了此Promise.setScheduler功能:
Promise.setScheduler
// 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); }); }]); }
现在我们要做的就是添加一个:
trackDigests(app);
一行接var app =...一行,一切都会按预期进行。为了获得奖励积分,请将Bluebird放入服务中,以便您可以注入它,而不是在全局名称空间上使用它。
var app =...
这是一个说明这种行为的 小提琴 。
请注意,除了Bluebird拥有的所有功能之外$q,更重要的功能之一是Bluebird 不会 运行$exceptionHandler,而是会自动跟踪未处理的拒绝,因此您可以throw自由使用Bluebird的诺言,Bluebird会解决它们。而且调用Promise.longStackTraces()可以帮助调试很多东西。
$exceptionHandler
throw
Promise.longStackTraces()