Typescript, decorate async function

冷暖自知 提交于 2020-07-05 04:22:10

问题


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.


回答1:


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));
}


来源:https://stackoverflow.com/questions/47512544/typescript-decorate-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!