Search code examples
javascriptasync-awaitecmascript-next

Can async/await be used in constructors?


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

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

Solution

  • 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.