可以在构造函数中使用async/await吗? [英] Can async/await be used in constructors?

查看:1313
本文介绍了可以在构造函数中使用async/await吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所述.我可以这样做吗?

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

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

推荐答案

在不试图讲述未来决策的情况下,让我们专注于实用性和已知的知识.

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

ES7与之前的ES6一样,将尝试向后扩展该语言.考虑到这一点,向后兼容的构造函数本质上是一个常规函数(具有一些运行时限制),该常规函数应使用new关键字进行调用.发生这种情况时,将对函数的返回值进行特殊处理,特别是将忽略非对象返回值,并返回新分配的对象,而按原样返回对象返回值(并丢弃新分配的对象).这样,您的代码将导致返回承诺,并且不会发生对象构造".我看不到这种做法的实用性,我想如果有人花时间去寻找处理此类代码的方法,它将被拒绝.

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.

这篇关于可以在构造函数中使用async/await吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆