【问题标题】:How to intercept Promises response in then or catch?如何在 then 或 catch 中拦截 Promises 响应?
【发布时间】:2018-01-23 20:11:03
【问题描述】:

我试图拦截所有 Promises then 方法的响应。但我无法在原型 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 调用中。但是我无法在 then 中获取响应对象。

控制台中打印的“this”对象值:

“then”原型方法中的打印参数:

请建议我在 then 方法中为所有 promises 方法获取响应对象。

我尝试使用“arguments[0].arguments”(然后回调中的响应对象)获取值。但是它抛出了以下错误

Uncaught TypeError: 'caller' 和 'arguments' 是受限函数 属性,并且无法在此上下文中访问。

请建议我拦截响应对象的解决方案。

提前致谢。

【问题讨论】:

  • 您愿意详细说明原因吗?

标签: javascript reactjs ecmascript-6 promise es6-promise


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    then() 在使用 Promise 以添加回调时被调用,在 Promise 实际具有值之前。
    它的参数是成功和错误回调。

    要查看 Promise 的值,您需要实际调用 then() 并传递回调以查看其最终值。 (或者包装你传递的回调并将你的包装器传递给真正的then()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-12
      • 2015-10-28
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多