打字稿,装饰异步功能

Sta*_*nko 3 decorator async-await typescript ecmascript-6

我正在尝试使用一些异步功能2装饰异步功能1。

例如

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
}
Run Code Online (Sandbox Code Playgroud)

因此,主要思想是在装饰器中执行一些异步操作,然后在main函数中执行其他异步调用。

可以使用打字稿装饰器来制作吗?

先感谢您。

Tit*_*mir 9

装饰器只能在类方法上使用,而不能在常规函数上使用,因此这是一个限制,但是如果将函数放在类中,则可以轻松替换原始函数并执行其他异步任务:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 我见过的最优雅的解决方案。 (2认同)