How do I use Bluebird with Angular?

前端 未结 2 2045
孤城傲影
孤城傲影 2020-11-27 02:25

I tried using Angular with Bluebird promises:

HTML:


    
{{
相关标签:
2条回答
  • 2020-11-27 03:07

    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.

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

    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.

    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.

    0 讨论(0)
  • 2020-11-27 03:09

    Library Angular bluebird promises replaces $q service with bluebird. $http also run through bluebird

    0 讨论(0)
提交回复
热议问题