2017-11-27 11 views
0

비동기 함수 # 1을 비동기 함수 # 2로 장식하려고합니다.Typescript, 비동기 함수를 장식하십시오.

예.

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 
} 

그래서, 주요 아이디어는 장식의 일부 비동기 작업을 수행하고 주요 기능의 다른 비동기 호출을 수행하는 것입니다.

타이코크 데코레이터를 만들 수 있습니까?

미리 감사드립니다. 그 한 가지 제한하므로

답변

0

장식 만이 아니라 일반 기능에 대한 클래스 메서드에 사용할 수 있지만, 당신은 클래스 내에서 기능을 넣을 경우 쉽게 다른 비동기 작업을 원래의 기능을 대체하고 수행 할 수 있습니다

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