45

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;

[Fiddle]

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.

How do I get Bluebird to work with AngularJS?

(I know it's possible since $q does it)

I'm using Bluebird 2.0 which I got here.

4

2 回答 2

61

这是可能的,甚至很容易!

好吧,如果我们看看Angular 自己的 Promise 是如何工作的,我们需要让 Bluebird 到$evalAsync某个地方才能获得完全相同的行为。

如果我们这样做,这两个实现都符合Promises/A+$q的事实意味着我们可以在代码和 Bluebird 代码之间进行互操作,这意味着我们可以在 Angular 代码中自由使用 Bluebird 的所有功能。

Bluebird 通过以下功能公开了此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 放入服务中,这样您就可以注入它而不是在全局命名空间中使用它。

这是一个 [ Fiddle ] 说明了这种行为。

请注意,除了 Bluebird 拥有的所有功能之外$q,更重要的一个是 Bluebird不会运行$exceptionHandler,而是会自动跟踪未处理的拒绝,因此您可以throw自由地使用 Bluebird 承诺,而 Bluebird 会弄清楚它们。此外,调用Promise.longStackTraces()可以帮助调试很多。

于 2014-06-01T21:06:08.520 回答
1

库Angular bluebird 承诺$q. 也穿过蓝鸟bluebird$http

于 2016-11-17T12:52:57.090 回答