首页 > 解决方案 > 异步函数可以在类字段中吗?

问题描述

考虑以下代码段:

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();

标签: javascriptasync-awaitecmascript-nextclass-fields

解决方案


异步函数可以在类字段中吗?

是的。

//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();

asyncECMAScript 2017 (ECMA-262)一起引入。

在您的代码片段中,您启用了Use Babel / ES 2015,它早于async.


推荐阅读