如何在执行任何类方法之前注入条件检查



我正在寻找有关如何优雅地处理异步数据检索的一些意见/解决方案。

在异步初始化任何具有某些数据的类时,我一直采用这样的方法:

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
  }
}

这个问题有什么解决方案吗?有什么设计模式可以解决这个问题吗?帮助赞赏!:)

你有没有想过根本不公开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());

现在基本上任何人都不可能以错误的方式使用它。 希望能给你一些想法。 祝你好运!

另一种选择是您可以将类的创建包装在函数中。假设必须在每个实例上调用init,您可以在创建时处理它:

(对不起,它不在打字稿中;我只是不太熟悉它。

const goAndGetDataFromWhoKnowsWhere = async () => 123;
const SomeClass = () => {
  class SomeClass {
    async init() {
      this.someProperty = await goAndGetDataFromWhoKnowsWhere();
      return this;
    }
  }
  return new SomeClass().init();
};
SomeClass().then(inst => {
  console.log('someProperty:', inst.someProperty);
});

与jcalz的答案类似,这不允许与new关键字一起使用:

new SomeClass(); // TypeError: SomeClass is not a constructor
<</div> div class="one_answers">

改用函数怎么样?

function SomeClass(){
  var newObj = Object.create(/* your prototype */)
  return goAndGetDataFromWhoKnowsWhere()
  .then((data) => {
    newObj.someProperty = data;
    return newObj;
  })
}
SomeClass().then((newObj) => {})

最新更新