async constructor functions in TypeScript?

前端 未结 8 1837
青春惊慌失措
青春惊慌失措 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条回答
  •  粉色の甜心
    2020-12-13 05:58

    A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return Promise<...> and await for it.

    You can:

    1. Make your public setup async.

    2. Do not call it from the constructor.

    3. Call it whenever you want to 'finalize' object construction.

      async function run() 
      {
          let topic;
          debug("new TopicsModel");
          try 
          {
              topic = new TopicsModel();
              await topic.setup();
          } 
          catch (err) 
          {
              debug("err", err);
          }
      }
      

提交回复
热议问题