Reputation: 1022
I have a very simple question, I've been looking around but I can't find the solution.
Take that code :
class Foo {
bar = () => {
return 'string'
}
baz = async() => {
return 'promise'
}
}
I want to know if a specific method of a class is async or not.
isAsync(Foo, 'bar') // false
isAsync(Foo, 'baz') // true
the thing is ... I DO NOT want to instantiate it. All the solutions I found uses "getOwnPropertyNames" on a class instance to get the functions.
Is it possible ?
Thanks ! 🍺
Upvotes: 0
Views: 102
Reputation: 816790
the thing is ... I DO NOT want to instantiate it. All the solutions I found uses "getOwnPropertyNames" on a class instance to get the functions.
Is it possible ?
In your specific example, bar
and baz
are instance class fields. It's the same as writing
class Foo {
constructor() {
this.bar = () => {
return 'string'
};
this.baz = async() => {
return 'promise'
};
}
}
The properties (and functions) don't exist until you actually created an instance of the class.
So the answer for this specific case is no.
If you declare the functions as "normal" class methods then you can simply look at the constructor function's prototype
property.
Upvotes: 1
Reputation: 3032
// the most simple way is
const isAsync = (someClass, name) => {
if (name in someClass.prototype)
return someClass.prototype[name][Symbol.toStringTag] === 'AsyncFunction'
const newInstance = new someClass()
if (name in newInstance)
return newInstance[name][Symbol.toStringTag] === 'AsyncFunction'
}
Upvotes: 1