Can async/await be used in constructors?

wintercounter picture wintercounter · Apr 1, 2016 · Viewed 19.8k times · Source

As the question stated. Will I be allowed to do this:

class MyClass {
    async constructor(){
        return new Promise()
    }
}

Answer

Dave P. picture Dave P. · Nov 29, 2017

To expand upon what Patrick Roberts said, you cannot do what you are asking, but you can do something like this instead:

class MyClass {
  constructor() {
     //static initialization
  }

  async initialize() {
     await WhatEverYouWant();
  }

  static async create() {
     const o = new MyClass();
     await o.initialize();
     return o;
  }
}

Then in your code create your object like this:

const obj = await MyClass.create();