5

Just as an exercise, I tried monkey-patching the Promise constructor, like so:

const pconstructor = global.Promise;
global.Promise = function (fn1) {
  this.foo = 'bar';
  pconstructor.call(this,fn1);
};

global.Promise.resolve = pconstructor.resolve;

however, I get an error when I call

Promise.resolve();

=>

TypeError: [object Object] is not a promise

Anyone know how to monkey-patch a constructor like this, properly?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

6

I'd recommend just writing a subclass of Promise:

const global = window; // (in browser...)


const OldPromise = global.Promise; 
global.Promise = class Promise extends OldPromise {
  constructor(executor) {
    // do whatever you want here, but must call super()
    console.log('hello, promise');

    super(executor); // call native Promise constructor
  }
};

Promise.resolve(); // prints: "hello, promise"

This takes care of all the nitty-gritty details behind the scenes when trying to monkey-patch a class like that.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • thanks this works with vanilla JS/ES6 ! but when using TypeScript to transpile, I get a bug :) https://github.com/Microsoft/TypeScript/issues/15294 – Alexander Mills Apr 20 '17 at 19:35