0

Update : I'm not asking for this Async/Await Class Constructor because as I said I want to keep the async INSIDE the constructor.

I can instantiate this class without problem except I cannot get its text property just after creation. Is there a simple way without changing too much the current structure (keep the async function inside the constructor and calling it from constructor)

  class Test {
    _text: string;

    get text() {
      return this._text;
    }
    constructor() {
        (async () => {
          this._text = await _init();
          console.log(this._text);
          return this;
        })();

      async function _init() {
        return "hello";
      }
    }

  }

  let test = new Test();
  let text = test.text;
  console.log(text);
user310291
  • 36,946
  • 82
  • 271
  • 487
  • 1
    "*I cannot get its text property just after creation.*" - well, yes, this is impossible if the value is only available asynchronously. [Don't put asynchronous stuff in a constructor](https://stackoverflow.com/q/24398699/1048572). – Bergi May 09 '22 at 03:02
  • @Bergi thanks for the link, think phaux gives the solution. – user310291 May 09 '22 at 08:18
  • No, don't do that, otherwise your `test.text` getter would need to return a promise. Instead, do your asynchronous stuff *before* creating the instance. – Bergi May 09 '22 at 11:18

0 Answers0