我正在寻找一些关于如何优雅地处理异步数据检索的意见/解决方案。
在用一些数据异步初始化任何类时,我一直采用这样的方法:
class SomeClass {
// Turning off ts compiler's strictPropertyInitialization
private someProperty: SomeType
public async init(): Promise<this> {
this.someProperty = await goAndGetDataFromWhoKnowsWhere();
return this;
}
public async aMethod(): Promise<AType> {
// do its thing
}
public async anotherMethod(): Promise<AnotherType> {
// do its thing
}
}
并期望用户(我自己/另一个同事)像这样使用此类:
const someResult = new SomeClass()
.init()
.then( thatClass => thatClass.aMethod() )
这种方法确实可以达到目的,但是没有硬性限制来确保 init()
被调用。有时,当有人忘记它时,事情就会崩溃。
我们可能可以打开strictPropertyInitialization
并在每个类方法中注入(inject)检查。这肯定有效,但是方法中的相同行正在大喊可能有更好的方法。
class SomeClass {
private someProperty: SomeType | undefined // To enforce null-checking
public async init(): Promise<this> {
this.someProperty = await goAndGetDataFromWhoKnowsWhere();
return this;
}
public async aMethod(): Promise<AType> {
if (!this.someProperty) await this.init();
// do its thing
}
public async anotherMethod(): Promise<AnotherType> {
if (!this.someProperty) await this.init();
// do its thing
}
}
这个问题有解决办法吗?有什么设计模式可以解决这个问题吗?帮助赞赏! :)
最佳答案
您是否考虑过完全不公开 new()
构造函数调用?如果您将构造函数设为私有(private),并公开一个静态 init()
方法,该方法异步构造一个实例并用数据填充它:
class SomeClass {
static async init(): Promise<SomeClass> {
return new SomeClass(await goAndGetDataFromWhoKnowsWhere());
}
private constructor(private someProperty: SomeType) { }
// your other methods
}
new SomeClass("oops"); // can't do this
SomeClass.init().then(thatClass => thatClass.aMethod());
现在基本上任何人都不可能以错误的方式使用它。希望能给你一些想法。祝你好运!
关于javascript - 如何在执行任何类方法之前注入(inject)条件检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348501/