bluebird.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. Zone.__load_patch('bluebird', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
  9. // TODO: @JiaLiPassion, we can automatically patch bluebird
  10. // if global.Promise = Bluebird, but sometimes in nodejs,
  11. // global.Promise is not Bluebird, and Bluebird is just be
  12. // used by other libraries such as sequelize, so I think it is
  13. // safe to just expose a method to patch Bluebird explicitly
  14. const BLUEBIRD = 'bluebird';
  15. (Zone as any)[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird: any) {
  16. // patch method of Bluebird.prototype which not using `then` internally
  17. const bluebirdApis: string[] = ['then', 'spread', 'finally'];
  18. bluebirdApis.forEach(bapi => {
  19. api.patchMethod(
  20. Bluebird.prototype, bapi, (delegate: Function) => (self: any, args: any[]) => {
  21. const zone = Zone.current;
  22. for (let i = 0; i < args.length; i++) {
  23. const func = args[i];
  24. if (typeof func === 'function') {
  25. args[i] = function() {
  26. const argSelf: any = this;
  27. const argArgs: any = arguments;
  28. return new Bluebird((res: any, rej: any) => {
  29. zone.scheduleMicroTask('Promise.then', () => {
  30. try {
  31. res(func.apply(argSelf, argArgs));
  32. } catch (error) {
  33. rej(error);
  34. }
  35. });
  36. });
  37. };
  38. }
  39. }
  40. return delegate.apply(self, args);
  41. });
  42. });
  43. Bluebird.onPossiblyUnhandledRejection(function(e: any, promise: any) {
  44. try {
  45. Zone.current.runGuarded(() => {
  46. throw e;
  47. });
  48. } catch (err) {
  49. api.onUnhandledError(err);
  50. }
  51. });
  52. // override global promise
  53. global[api.symbol('ZoneAwarePromise')] = Bluebird;
  54. };
  55. });