I'm trying to decorate async function#1 with some async function#2.
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
}
So, the main idea is to perform some async operation in decorator, and then perform other async calls in the main function.
Is it possible to make this withing typescript decorators?
Thank you in advance.
Decorators can only be used on a class method not on a regular function, so that is one limitation, but if you put the function within a class you can easily replace the original function and perform other async tasks:
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With