Typescript, decorate async function

后端 未结 1 1117
北恋
北恋 2021-02-09 17:15

I\'m trying to decorate async function#1 with some async function#2.

E.g.

function func2(param) {
   return (target: any, propertyKey: string, descriptor         


        
相关标签:
1条回答
  • 2021-02-09 18:05

    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));
    }
    
    0 讨论(0)
提交回复
热议问题