在Typescript中使用async/await时未定义__awaiter [英] __awaiter is not defined when using async/await in Typescript

查看:922
本文介绍了在Typescript中使用async/await时未定义__awaiter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Typescript中有以下代码段:

I have the following code snippet in 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));
}

但是,当它编译(v2.2.1)并运行时,出现以下错误:

However, when this is compiled (v2.2.1) and run, I get the following error:

未捕获的ReferenceError:未定义__awaiter

Uncaught ReferenceError: __awaiter is not defined

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

What does this mean and how do I get the expected functionality?

{
  "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"
  ]
}

推荐答案

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

When you use some functionalities from future version of JavaScript (ES6 and beyond) like in your case async/await, TypeScript generates helper functions. These helper functions are used to provide the new functionalities as ES5 code, thus it can be run in a web browser.

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

In your tsconfig.json you set the noEmitHelpers value to true. By doing that you tell the TypeScript compiler that you will provide these helper functions yourself.

  • 您可以在tsconfig.json中将noEmitHelpers值设置为false,因此TypeScript编译器将在需要时发出辅助函数.这种方法的一个缺点是,例如,如果在2个不同的文件中使用async/await,则辅助函数将发出2次(每个文件1个).
  • 另一种解决方案是在使用tsc时设置--importHelpers标志.它将告诉TypeScript编译器仅包含一次辅助函数.请注意,如果使用此解决方案,则必须安装tslib软件包.
  • You can set the noEmitHelpers value to false in your tsconfig.json, thus the TypeScript compiler will emit the helper functions when needed. One drawback of this method is that if you use for example async/await in 2 different files, the helper functions will be emitted 2 times (one per file).
  • The other solution is to set the --importHelpers flag when you use tsc. It will tell the TypeScript compiler to include the helper functions only once. Please note that if you use this solution you have to install the tslib package.

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

这篇关于在Typescript中使用async/await时未定义__awaiter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆