装饰器 如何 装饰异步方法
网上一波Decorator 的介绍,给类的方法增加装饰器的都是
let log = (type) => {
return (target, name, descriptor) => {
const method = descriptor.value;
descriptor.value = (...args) => {
console.info(`(${type}) 正在执行: ${name}(${args}) = ?`);
let ret;
try {
ret = method.apply(target, args);
console.info(`(${type}) 成功 : ${name}(${args}) => ${ret}`);
} catch (error) {
console.error(`(${type}) 失败: ${name}(${args}) => ${error}`);
}
return ret;
}
}
}
class Super{
@log('some_log')
fetchData(){
...
}
}
这么个操作。
但是如果被装饰fn 是一个promise、异步方法的话,如何做到
// 想在这里来一波log,上面的方法是可以做到的
fetch('http://xxx.xxx.com')
.then((res)=>{
// 想在这里来一波log ,怎么搞?
})
目前我的操作是 fn.toString() 插入一些代码, eval() 成一个方法。
有一些优雅的方法来做这件事么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议用 中间件
promise return 后处理顺序在原代码执行顺序后面,类似这种
可以参考 axios
本质都是js,举一反三一下就行了啊