zone-bluebird.js 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2022 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. Zone.__load_patch('bluebird', (global, Zone, api) => {
  8. // TODO: @JiaLiPassion, we can automatically patch bluebird
  9. // if global.Promise = Bluebird, but sometimes in nodejs,
  10. // global.Promise is not Bluebird, and Bluebird is just be
  11. // used by other libraries such as sequelize, so I think it is
  12. // safe to just expose a method to patch Bluebird explicitly
  13. const BLUEBIRD = 'bluebird';
  14. Zone[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird) {
  15. // patch method of Bluebird.prototype which not using `then` internally
  16. const bluebirdApis = ['then', 'spread', 'finally'];
  17. bluebirdApis.forEach(bapi => {
  18. api.patchMethod(Bluebird.prototype, bapi, (delegate) => (self, args) => {
  19. const zone = Zone.current;
  20. for (let i = 0; i < args.length; i++) {
  21. const func = args[i];
  22. if (typeof func === 'function') {
  23. args[i] = function () {
  24. const argSelf = this;
  25. const argArgs = arguments;
  26. return new Bluebird((res, rej) => {
  27. zone.scheduleMicroTask('Promise.then', () => {
  28. try {
  29. res(func.apply(argSelf, argArgs));
  30. }
  31. catch (error) {
  32. rej(error);
  33. }
  34. });
  35. });
  36. };
  37. }
  38. }
  39. return delegate.apply(self, args);
  40. });
  41. });
  42. if (typeof window !== 'undefined') {
  43. window.addEventListener('unhandledrejection', function (event) {
  44. const error = event.detail && event.detail.reason;
  45. if (error && error.isHandledByZone) {
  46. event.preventDefault();
  47. if (typeof event.stopImmediatePropagation === 'function') {
  48. event.stopImmediatePropagation();
  49. }
  50. }
  51. });
  52. }
  53. else if (typeof process !== 'undefined') {
  54. process.on('unhandledRejection', (reason, p) => {
  55. if (reason && reason.isHandledByZone) {
  56. const listeners = process.listeners('unhandledRejection');
  57. if (listeners) {
  58. // remove unhandledRejection listeners so the callback
  59. // will not be triggered.
  60. process.removeAllListeners('unhandledRejection');
  61. process.nextTick(() => {
  62. listeners.forEach(listener => process.on('unhandledRejection', listener));
  63. });
  64. }
  65. }
  66. });
  67. }
  68. Bluebird.onPossiblyUnhandledRejection(function (e, promise) {
  69. try {
  70. Zone.current.runGuarded(() => {
  71. e.isHandledByZone = true;
  72. throw e;
  73. });
  74. }
  75. catch (err) {
  76. err.isHandledByZone = false;
  77. api.onUnhandledError(err);
  78. }
  79. });
  80. // override global promise
  81. global.Promise = Bluebird;
  82. };
  83. });