async constructor functions in TypeScript?

前端 未结 8 1862
青春惊慌失措
青春惊慌失措 2020-12-13 05:43

I have some setup I want during a constructor, but it seems that is not allowed

Which means I can\'t use:

How else should I do this?

<
8条回答
  •  猫巷女王i
    2020-12-13 05:50

    I've found a solution that looks like

    export class SomeClass {
      private initialization;
    
      // Implement async constructor
      constructor() {
        this.initialization = this.init();
      }
    
      async init() {
        await someAsyncCall();
      }
    
      async fooMethod() {
        await this.initialization();
        // ...some other stuff
      }
    
      async barMethod() {
        await this.initialization();
        // ...some other stuff
      }
    
    

    It works because Promises that powers async/await, can be resolved multiple times with the same value.

提交回复
热议问题