javascript - 异步函数可以在类字段中吗?
问题描述
考虑以下代码段:
class Foo {
method = () => {
console.log('method');
}
}
const f = new Foo();
f.method();
工作得很好。但是,如果函数改为异步,则没有其他更改:
class Foo {
method = async () => {
console.log('method');
}
}
const f = new Foo();
f.method();
这会导致语法错误。无论是否使用箭头函数,它都会发生:
class Foo {
method = function() {
console.log('method');
}
}
const f = new Foo();
f.method();
class Foo {
method = async function() {
console.log('method');
}
}
const f = new Foo();
f.method();
我的语法是否不正确,或者类字段中只是禁止了异步函数?
(当然,原型上的普通异步方法也是可能的,但我在问类字段中的异步函数为什么/如何工作)
接受评论的建议async method() => {
也不起作用:
class Foo {
async method() => {
console.log('method');
}
}
const f = new Foo();
f.method();
解决方案
异步函数可以在类字段中吗?
是的。
//Without BabelJS / ES2015
class Foo {
method = async () => {
console.log('method');
}
}
const f = new Foo();
f.method();
使用 ES2015 转译器时,异步函数可以在类字段中吗?
不。
//Without BabelJS / ES2015
class Foo {
method = async () => {
console.log('method');
}
}
const f = new Foo();
f.method();
async
与ECMAScript 2017 (ECMA-262)一起引入。
在您的代码片段中,您启用了Use Babel / ES 2015,它早于async
.
推荐阅读
- postgresql - 在关系数据库中创建用户后调用脚本是否可取?
- mongodb - 重新安装后Mongodb无法识别过去的数据文件(.wt)
- xcode - 如何在外部 ssd 中安装 xcode 11.7
- python - 加载 python 包需要很长时间(3.5 on Anaconda for Windows)
- c# - 如何获取 Dynamics 365 令牌?
- c# - Visual Studio C# SerialPort 数据转 ASCII - Encoding.ASCII.GetString(data, 0, data.Length);
- r - 将因子转换为数值返回零
- node.js - Electron 中的自签名证书
- opengl - 如何在vmware中将opengl升级到3.3
- solr - updateRequestProcessorChain 不适用于 Solr 文档