0

I looking for a way to detect if my function inside the decorator is async or not.

function catchError(target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    if(/* method is async function */) {
        
    }
}
class Foo {
    @catchError
    public bar(message: string) {
        //do somthing
    }
}

I tried to looking for option to do that and didn't find anything, maybe there is no way but why?

Nullndr
  • 1,624
  • 1
  • 6
  • 24
elija
  • 21
  • 3

1 Answers1

1

You have to check for the constructor.name property of the function:

async function foo() {}

console.log(foo.constructor.name); // "AsyncFunction"

function bar() {}

console.log(bar.constructor.name); // "Function"

So in your case it will be:

const method = descriptor.value;

if(method.constructor.name === "AsyncFunction") {
  // method is an async function
} else {
  // method is not an async function
}
Nullndr
  • 1,624
  • 1
  • 6
  • 24
  • This will catch if it is declared with the `async` keyword, but not if it is a regular function that returns a Promise. I *really* wouldn't depend on this as it breaks duck typing. – Quentin Dec 12 '22 at 09:14