Hariharan Subramanian
Hariharan Subramanian

Reputation: 1531

How to intercept Promises response in then or catch?

I am trying to intercept the response from all Promises then method. But i am not able to get the response data in the prototype then method. please find below code.

(function(Promise) {
   var originalThen = Promise.prototype.then;
   var originalCatch = Promise.prototype.catch;
   Promise.prototype.then = function() {
      console.log(this, arguments);
      return originalThen.apply(this, arguments);
   };
   Promise.prototype.catch = function() {
      return originalCatch.apply(this, arguments);
   };
})(this.Promise)

In the above code I can see the console printed in all Promise call. But i cannot get the response object in the then.

The Printed 'this' object value in console:

enter image description here

The printed arguments inside the 'then' prototype method:

enter image description here

Please suggest me to get the response object in then method for all promises method.

I tried to get the value using "arguments[0].arguments" (Response object in the then callback).But its throwing the below error

Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.

Please suggest me the solution to intercept the response object.

Thanks in advance.

Upvotes: 2

Views: 1669

Answers (2)

jib
jib

Reputation: 42430

then is a synchronous method that registers success and failure callbacks. It returns immediately.

To intercept a future value, insert yourself in place of the success callback:

(function(Promise) {
   var originalThen = Promise.prototype.then;
   Promise.prototype.then = function(onFulfilled, onFailure) {
      return originalThen.call(this, function(value) {
        console.log(value);
        return onFulfilled(value);
      }, onFailure);
   };
})(this.Promise);

Promise.resolve(3).then(() => console.log("Done"));

Upvotes: 3

SLaks
SLaks

Reputation: 887305

then() is called when consuming a promise to add a callback, before the promise actually has a value.
Its arguments are the success and error callbacks.

To see the promise's value, you need to actually call then() and pass a callback to see its eventual value. (or wrap the callbacks you were passed and pass your wrappers to the real then())

Upvotes: 2

Related Questions