shimCall.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. /*
  3. * cls-bluebird
  4. * Function to shim `Promise.prototype.call`
  5. */
  6. // Modules
  7. var shimmer = require('shimmer');
  8. // Exports
  9. var hasOwnProperty = Object.prototype.hasOwnProperty;
  10. /**
  11. * Patch `call` method to run 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, 'call', function(callOriginal) {
  20. return function() {
  21. // Temporarily wrap `this._then` to bind the object method to current CLS context
  22. // (`this.call()` will call `this._then()` synchronously)
  23. var _thenOriginal = this._then,
  24. ownProperty = hasOwnProperty.call(this, '_then');
  25. this._then = function() {
  26. // Unwrap `this._then`
  27. if (ownProperty) {
  28. this._then = _thenOriginal;
  29. } else {
  30. delete this._then;
  31. }
  32. // Bind function that will be called to call object method to CLS context
  33. arguments[0] = ns.bind(arguments[0]);
  34. // Run original `this._then` method
  35. return _thenOriginal.apply(this, arguments);
  36. };
  37. // Call original `call` method
  38. return callOriginal.apply(this, arguments);
  39. };
  40. });
  41. };