16

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" ] } 
3
  • Could you share your tsconfig.json ? And the command you use to compile your code. Commented Feb 23, 2017 at 13:55
  • @Romain Sure - here is the tsconfig, I run this with just tsc -w from the directory with that tsconfig in it's root. Commented Feb 23, 2017 at 14:02
  • If the posted answer resolves your problem, please mark it as accepted Commented Mar 14, 2017 at 7:21

2 Answers 2

24

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

Sign up to request clarification or add additional context in comments.

Comments

17

The accepted answer didn't work in my case, but I found that my tsconfig.json was targeting es6 ("target":"es6").

What this means is that TypeScript transpiles to code that uses the __awaiter util because async await was not included in the spec until ES2017.

I fixed this by changing my target to ESNext (or anything ES2017 and above)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.