【问题标题】:Can async functions be in class fields?异步函数可以在类字段中吗?
【发布时间】:2019-07-16 01:59:24
【问题描述】:

考虑以下 sn-p:

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

【问题讨论】:

  • 您绝对应该在问题中提及您在 sn-ps 中启用了 Use Babel。没有它,您的代码可以正常工作。 Uncaught SyntaxError: Inline Babel script: Unexpected token (3:20)

标签: javascript async-await ecmascript-next class-fields


【解决方案1】:

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

是的。

//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) 介绍的。

在您的 sn-ps 中,您已启用 Use Babel / ES2015,它早于 async

【讨论】:

  • 所以转译器支持类字段,即使它们仅处于第 3 阶段,(也许它们将被集成到 ES2020 中?)而 async 不受支持,尽管在规范中现在有一段时间了?这很令人惊讶,我原以为情况会相反。转译器似乎也不支持普通异步函数
  • 我同意你的不一致之处,但不幸的是我没有很好的答案。 如果我不得不猜测,它使用了一个允许类属性的 Babel 插件(当时处于 Stage 1),正如 in this article from 2016 所讨论的那样。
【解决方案2】:

问:这对你有用吗:

class Foo {
  async method () {
    console.log('method');
  }
}
const f = new Foo();
f.method();

【讨论】:

  • 不过,这并没有使用类字段 - 我在问我的实现有什么问题。我很清楚如何在类中使用普通方法
【解决方案3】:

根据mozilla,IE 不支持此语法,我猜测您在那里遇到错误,您的第二个示例工作在 chrome 中打招呼。

class Foo {
  method = async () => {
    console.log('method');
  }
}
const f = new Foo();
f.method();

【讨论】:

  • 所有的 sn-ps 都在被转译。如果您在 Internet Explorer 上打开此页面,您将看到第一个和第三个 sn-ps 正常工作。
  • 在 IE 11 上测试了上述内容,但没有成功,如果您阅读浏览器兼容性,您会发现语法不支持 IE
  • @Alen.Toma OP 正在使用转译器 (Babel),特别是因为浏览器兼容性。这就是转译器的作用。
  • @Alen.Toma 在 IE 中查看我的屏幕截图:它按预期工作 i.stack.imgur.com/OUxip.png
猜你喜欢
  • 2014-06-14
  • 2011-12-30
  • 1970-01-01
  • 2019-08-18
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多