Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, decorate async function

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.

like image 468
Stanislav Kharchenko Avatar asked Nov 27 '17 13:11

Stanislav Kharchenko


1 Answers

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));
}
like image 136
Titian Cernicova-Dragomir Avatar answered Oct 22 '22 15:10

Titian Cernicova-Dragomir