shimOnCancel.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. /*
  3. * cls-bluebird
  4. * Function to shim `Promise.prototype._resolveFromExecutor`
  5. * in order to patch `onCancel` handler in `new Promise()`.
  6. */
  7. // Modules
  8. var shimmer = require('shimmer');
  9. // Exports
  10. /**
  11. * Patch `_resolveFromExecutor` proto method to run `onCancel` callbacks in current CLS context.
  12. *
  13. * @param {Function} Promise - Bluebird Promise constructor to patch
  14. * @param {Object} ns - CLS namespace to bind callbacks to
  15. * @returns {undefined}
  16. */
  17. module.exports = function(Promise, ns) {
  18. // Patch method
  19. shimmer.wrap(Promise.prototype, '_resolveFromExecutor', function(_resolveFromExecutorOriginal) {
  20. return function(executor) {
  21. // Patch executor
  22. var executorPatched = function() {
  23. var onCancel = arguments[2];
  24. if (onCancel) {
  25. // Patch onCancel function
  26. arguments[2] = function(fn) {
  27. // Bind onCancel handler to current CLS context
  28. if (typeof fn === 'function') fn = ns.bind(fn);
  29. return onCancel.call(this, fn);
  30. };
  31. }
  32. return executor.apply(this, arguments);
  33. };
  34. // Call original method
  35. return _resolveFromExecutorOriginal.call(this, executorPatched);
  36. };
  37. });
  38. };