I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronous. I am aware that it is not possible to await the constructor itself, but I have discovered that an async function used inside the constructor is awaited. This seems counterintuitive, but it actually works. Can anyone confirm or explain why this works?
For example:
abstract class Base {
constructor() {
// perform some setup
this.asyncMethod();
}
abstract asyncMethod(): Promise<void>;
}
class Test extends Base {
constructor() {
super();
}
async asyncMethod(): Promise<void> {
await setTimeout(() => console.log('Tadaaaa'));
}
}
const instance = new Test();