__awaiter is not defined when using async/await in Typescript

荒凉一梦 提交于 2019-12-20 01:05:32

问题


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

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

Uncaught ReferenceError: __awaiter is not defined

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

Update:

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

回答1:


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.

Your problem:

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.

How to fix it:

  • 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.

In your case: tsc --importHelpers -w



来源:https://stackoverflow.com/questions/42415450/awaiter-is-not-defined-when-using-async-await-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!