打字稿,装饰异步功能 [英] Typescript, decorate async function

查看:68
本文介绍了打字稿,装饰异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如

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
}

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

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?

谢谢.

推荐答案

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

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

这篇关于打字稿,装饰异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆