Seeking input on handling async data retrieval elegantly.
When initializing a class with asynchronous data, I have been following this approach:
class SomeClass {
// Disabling strictPropertyInitialization
private someProperty: SomeType
public async init(): Promise<this> {
this.someProperty = await goAndGetDataFromWhoKnowsWhere();
return this;
}
public async aMethod(): Promise<AType> {
// do something
}
public async anotherMethod(): Promise<AnotherType> {
// do something
}
}
Users (myself / co-worker) are expected to use the class like this:
const someResult = new SomeClass()
.init()
.then( thatClass => thatClass.aMethod() )
This method works fine, but there is no assurance that the init()
will always be called. In case it gets missed, issues arise.
We could enable strictPropertyInitialization
and add checks in every class method. While effective, repeating similar lines in each method suggests room for improvement.
class SomeClass {
private someProperty: SomeType | undefined // For enforcing null-check
public async init(): Promise<this> {
this.someProperty = await goAndGetDataFromWhoKnowsWhere();
return this;
}
public async aMethod(): Promise<AType> {
if (!this.someProperty) await this.init();
// do something
}
public async anotherMethod(): Promise<AnotherType> {
if (!this.someProperty) await this.init();
// do something
}
}
Are there any solutions or design patterns to address this issue? Appreciate any help! :)