Can async/await be used in constructors?

前端 未结 4 1682
时光取名叫无心
时光取名叫无心 2020-12-14 16:21

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

class MyClass {
    async constructor(){
        return new Promise()
    }
}
4条回答
  •  再見小時候
    2020-12-14 16:59

    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();
    

提交回复
热议问题