【问题标题】:Typescript: Async * iterator closure not compiling打字稿:异步*迭代器闭包未编译
【发布时间】:2018-05-02 20:45:52
【问题描述】:

为什么下面的例子不能编译?基本上,问题是如何正确声明异步可迭代闭包。

class Test {
  async foo() {
    const c = async () => {
    };
    await c();
  }

  async * bar() {
    const c = async * () => {
    };
    yield * c();
  } 
}

错误是:

...: error TS1109: Expression expected.
...: error TS1005: ';' expected.

我的 tsconfig.json:

{
  "compilerOptions": {
    "declaration": true,
    "lib": [
      "es2017",
      "dom",
      "esnext.asynciterable"
    ],
    "module": "commonjs",
    "target": "es2015",
    "sourceMap": true,
    "outDir": "out",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
  },
  "include": [
      "src/**/*.ts"
  ]
}

如果我将示例更改为以下内容,它会起作用。我使用函数而不是箭头语法:

class Test {
  async foo() {
    const c = async () => {
    };
    await c();
  }

  async * bar() {
    const c = async function *() {
    };
    yield * c();
  } 
}

【问题讨论】:

  • 失败是什么错误?
  • 能否请您显示您的 tsconfig.json 的内容?

标签: typescript asynchronous async-await


【解决方案1】:

目前还不支持使用异步生成器的箭头函数;即const c = async *()=> {};

与生成器一样,异步生成器只能起作用 类或对象的声明、函数表达式或方法 文字。 箭头函数不能是异步生成器。

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html

【讨论】:

    【解决方案2】:

    Arrow function ()=>{} 和常规函数有一些不同之处。

    例如箭头函数没有this 绑定。

    此外,有关生成器的文档明确指出,您必须使用 function 语法,因为它使用 this 进行迭代。

    这就是异步生成器不支持箭头函数的原因

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多