2017-08-15 155 views
1

我想拦截所有承诺然后方法的响应。但我无法在原型和方法中获得响应数据。请找到下面的代码。如何拦截Promises响应或捕获?

(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) 

在上面的代码中,我可以看到在所有Promise调用中打印的控制台。但是我无法获得当时的响应对象。

印刷 '这个' 对象在控制台值:

enter image description here

的 '然后' 原型方法中的印刷参数:

enter image description here

请建议我在所有promise方法的then方法中获得响应对象。

我就先用“的论点[0] .arguments”(在当时的回调Response对象),但它抛出下面的错误

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

请建议我解决拦截响应值目的。

在此先感谢。

+1

你将高达拟订关于为什么呢? – loganfsmyth

回答

2

then()在承诺实际上具有值之前消费承诺来添加回调时被调用。
它的参数是成功和错误回调。

要查看承诺的价值,您需要实际拨打then()并传递回调以查看其最终价值。 (或者包装您通过的回调并将您的包装传递给真实的then()

3

then是一种同步方法,用于注册成功和失败回调。它立即返回。

拦截未来值,插入自己在地方的成功回调:

(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"));