title: Unable to Override methods on Promise class - Promise.prototype.then called on incompatible receiver undefined
body: <p>I am trying to override <code>then</code>, <code>catch</code> and <code>finally</code> functions. This is to create a global counter and monitor the pending promises. </p>
  
  <p>The code needs to be executed Postman Sandbox, so I cannot use any NPM modules. I needs to do this with Native JS</p>
  
  <p>Below is the code that I am trying to work out</p>
  
  <pre><code>_constructor = Promise.prototype.constructor
  _then = Promise.prototype.then
  
  Promise.prototype.constructor = (...args) =&gt; {
      console.log("Promise constructor called")
      let data = _constructor(...args)
      console.log("Promise constructor finished")
      return data;
  }
  
  Promise.prototype.then = (...args) =&gt; {
      console.log("then called")
      let data = _then.call(this, args)
      console.log("then finished")
      return data;
  }
  
  function test2(num) {
      let promise = new Promise((resolve, reject) =&gt; {
          if (num &gt; 1) {
              setTimeout(()=&gt; {
                  resolve(num)
              }, 10)
          } else {
              reject(num);
          }
      });
      return promise
  }
  
  test2(10).then((num) =&gt; {
      console.log("Inside then")
      setTimeout(() =&gt; console.log("Promise has been resolved - " + num), 20);
  })
  </code></pre>
  
  <p>But when I run this I get below error</p>
  
  <pre><code>    let data = _then.call(this, args)
                       ^
  
  TypeError: Method Promise.prototype.then called on incompatible receiver #&lt;Object&gt;
      at Object.then (&lt;anonymous&gt;)
      at Promise.then.args (/Users/tarun.lalwani/Desktop/test/postman/temp.jsx:15:22)
      at Object.&lt;anonymous&gt; (/Users/tarun.lalwani/test/postman/temp.jsx:33:11)
      at Module._compile (module.js:660:30)
      at Object.Module._extensions..js (module.js:671:10)
      at Module.load (module.js:573:32)
      at tryModuleLoad (module.js:513:12)
      at Function.Module._load (module.js:505:3)
      at Function.Module.runMain (module.js:701:10)
      at startup (bootstrap_node.js:193:16)
  </code></pre>
  
  <p>I am not sure what is wrong here, or is this the right way to do it or not.</p>