如何重写promise的catch方法?

Promise.prototype.catch = function(){console.log(1)}
这样就被我覆盖了,原来的catch呢?
好像要用call apply来写?怎么写呢?

阅读 3.7k
3 个回答

为什么要重写catch呢,要处理异常,在promise对象的catch方法里面写自己的逻辑不能满足需求吗?

先用变量引用一下,然后再放回去就行了:

var originCatch = Promise.prototype.catch;
Promise.prototype.catch = function(...arg){
    // 注入其他代码
    // ...
    
    // 绑定 promise 实例,传入参数
    originCatch.bind(this)(...arg);
    
    // 或者用 apply
    // originCatch.apply(this, arguments);
}

找不回来了,已经被永久覆盖了。

在覆盖之前,你应该保存一份原始的 catch

const originCatch = Promise.prototype.catch
Promise.prototype.catch = function(){console.log(1)}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题