我正在尝试用一些异步函数#2 来装饰异步函数#1。
E.g.
function func2(param) {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
//make async operations and then return descriptor
}
@func2(param)
async function func1() {
await .... //some async operation
await .... //some async operation
}
因此,主要思想是在装饰器中执行一些异步操作,然后在主函数中执行其他异步调用。
是否可以使用打字稿装饰器来实现这一点?
先感谢您。
装饰器只能在类方法上使用,而不能在常规函数上使用,因此这是一个限制,但如果将函数放在类中,则可以轻松替换原始函数并执行其他异步任务:
function func2(param: number) {
return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<(... params: any[])=> Promise<any>>) => {
let oldFunc = descriptor.value;
descriptor.value = async function (){
var result = await oldFunc.apply(this, arguments);
await delay(param) //some async operation
console.log("delay 3");
return result;
}
}
}
class Test {
@func2(1000)
async func1(timout: number) {
await delay(timout) //some async operation
console.log("delay 1");
await delay(timout) //some async operation
console.log("delay 2");
}
}
new Test().func1(1000);
// Util function
async function delay(timeout: number) {
return new Promise<void>((resolve) => setTimeout(() => {
resolve();
}, timeout));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)