在Typescript中使用async/await时未定义__awaiter

Geo*_*rds 3 asynchronous async-await typescript

我在Typescript中有以下代码片段:

nsp.on('connection', async function (socket) {
    await this.emitInitialPackage(nsp, currentLine, currentCell);
}

emitInitialPackage(nsp: any, name: string, cell: any) {
    return db.Line.find({
        where: {
            name: name,
            CellId: cell
        }
    }).then(results => {
        nsp.emit('value', results);
    }).catch(err => console.log(err));
}
Run Code Online (Sandbox Code Playgroud)

但是,当编译(v2.2.1)并运行时,我收到以下错误:

未捕获的ReferenceError:未定义__awaiter

这是什么意思,我如何获得预期的功能?

更新:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "strictNullChecks": false,
    "lib": [
      "dom",
      "es2015.promise", 
      "es5"
    ],
    "types": [
      "node", 
      "express"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*mie 11

接受的答案在我的情况下不起作用,但我发现我的tsconfig.json目标是es6"target":"es6")。

这意味着 TypeScript 会转换为使用__awaiterutil 的代码,因为直到 ES2017async await包含在规范中

我通过更改targetESNext(或ES2017以上任何内容)来解决此问题


Rom*_*ain 10

当您使用未来版本的JavaScript(ES6及更高版本)中的某些功能时async/await,请TypeScript生成辅助函数.这些辅助函数用于提供ES5代码的新功能,因此可以在Web浏览器中运行.

你的问题:

tsconfig.json你的设置noEmitHelpers值为true.通过这样做,您告诉TypeScript编译器您将自己提供这些帮助程序功能.

如何解决:

  • 你可以设定noEmitHelpers值,false在您的tsconfig.json,因此TypeScript编译器在需要时会发出辅助功能.此方法的一个缺点是,如果您async/await在2个不同的文件中使用,则辅助函数将发出2次(每个文件一个).
  • 另一种解决方案是--importHelpers在使用时设置标志tsc.它将告诉TypeScript编译器只包含一次辅助函数.请注意,如果您使用此解决方案,则必须安装该tslib软件包.

在你的情况下: tsc --importHelpers -w