js 插桩 hooks 异步函数怎么处理?

比如正常的hooks

function withHookBefore (originalFn, hookFn) {
  return function () {
    if (hookFn.apply(this, arguments) === false) {
      return
    }
    return originalFn.apply(this, arguments)
  }
}

修改console

window.console = withHookBefore(console.log,window.alert);

假设我现在要console的时候去请求接口上报console的内容。

因为是异步的,就实现不了。该怎么处理?

阅读 2.1k
1 个回答

异步处理,比如:

function withHookBefore (originalFn, hookFn) {
    return function () {
        return Promise.resolve(hookFn.apply(this, arguments))
        .then(() => originalFn.apply(this, arguments))
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题