Javascript 如何在执行任何类方法之前注入条件检查
我正在寻找一些关于如何优雅地处理异步数据检索的意见/解决方案 在用一些数据异步初始化任何类时,我一直采用如下方法:Javascript 如何在执行任何类方法之前注入条件检查,javascript,typescript,oop,asynchronous,Javascript,Typescript,Oop,Asynchronous,我正在寻找一些关于如何优雅地处理异步数据检索的意见/解决方案 在用一些数据异步初始化任何类时,我一直采用如下方法: class SomeClass { // Turning off ts compiler's strictPropertyInitialization private someProperty: SomeType public async init(): Promise<this> { this.someProperty = await goAn
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并在每个类方法中注入检查。这肯定行得通,但方法中的相同行正在呼喊可能有更好的方法
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
}
}
这个问题有什么解决办法吗?有解决这个问题的设计模式吗?感谢您的帮助!: 您是否考虑过根本不公开新的构造函数调用?如果将构造函数设为私有,并公开一个静态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());
现在,任何人都不可能以错误的方式使用它。希望这能给你一些想法。祝你好运 另一个选项是可以将类的创建包装到函数中。假设必须在每个实例上调用init,您可以在创建时处理它: 对不起,它不是用打字机写的;我只是不太熟悉。 const goand getdatafromwhowowowwhere=async=>123; const SomeClass==>{ 上课{ 异步初始化{ this.someProperty=await goand getdatafromwhowknowswhere; 归还这个; } } 返回新的SomeClass.init; }; SomeClass.theninst=>{ console.log'someProperty:',inst.someProperty;
}; 不如改用函数呢
function SomeClass(){
var newObj = Object.create(/* your prototype */)
return goAndGetDataFromWhoKnowsWhere()
.then((data) => {
newObj.someProperty = data;
return newObj;
})
}
SomeClass().then((newObj) => {})
问题是,链中是否调用了init?