javascript - 如何在执行任何类方法之前注入(inject)条件检查

标签 javascript typescript oop asynchronous

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

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

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/

相关文章:

javascript - 如何在 JavaScript 中将数组中的值添加到另一个数组中的值?

java - 为一名观察者提供多个主题的正确设计模式

sql - 如何在typeorm querybuilder中选择特定列

javascript - 我如何像 React 一样在 Angular 2+ 中传递 Prop ?

angular - 如何将条件错误检查从 NgIf 移至 typescript 文件?

javascript - 面向对象 : jQuery class method call on click event

c# - 成员变量和成员属性之间的区别?

javascript - 在 p5.js 中生成一个随机整数

javascript - 获取我的屏幕的宽高并修改它以适应任何设备

javascript - $ ("#myForm").attr ("action") 返回一个表单元素,而不是没有操作的表单的 undefined