Can async/await be used in constructors?

前端 未结 4 1692
时光取名叫无心
时光取名叫无心 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:51

    Without trying to fortune-tell about future decisions, let's concentrate on practicality and what is already known.

    ES7, like ES6 before it will try to be a backwards compatible expansion to the language. With that in mind, a backwards compatible constructor function is essentially a regular function (with some runtime restrictions) that's meant to be invoked with the new keyword. When that happens, the function's return value gets special treatment, specifically, non-object return values are ignored and the newly allocated object is returned while object return values are returned as is (and the newly allocated object is thrown away). With that, your code would result in a promise being returned and no "object construction" would take place. I don't see the practicality of this and I suppose if anybody takes the time to find what to do with such code it will be rejected.

提交回复
热议问题