async / await是否允许我们在构造函数上使用? [英] Does async/await will allow us to be used on constructors?

查看:591
本文介绍了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天全站免登陆