我试图拦截所有 Promise then 方法的响应。但我无法在原型(prototype) then 方法中获取响应数据。请找到下面的代码。
(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 调用中打印的控制台。但我当时无法获取响应对象。
控制台中打印的“this”对象值:
“then”原型(prototype)方法中打印的参数:
请建议我在所有 Promise 方法的 then 方法中获取响应对象。
我尝试使用“arguments[0].arguments”(then 回调中的响应对象)获取值。但它抛出以下错误
Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
请建议我拦截响应对象的解决方案。
提前致谢。
最佳答案
then
是一个注册成功和失败回调的同步方法。它立即返回。
要拦截 future 值,请将您自己插入到成功回调的位置:
(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"));
关于javascript - 如何拦截 then 或 catch 中的 Promise 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45700756/