问题
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 tofalse
in yourtsconfig.json
, thus theTypeScript
compiler will emit the helper functions when needed. One drawback of this method is that if you use for exampleasync/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 usetsc
. It will tell theTypeScript
compiler to include the helper functions only once. Please note that if you use this solution you have to install thetslib
package.
In your case: tsc --importHelpers -w
来源:https://stackoverflow.com/questions/42415450/awaiter-is-not-defined-when-using-async-await-in-typescript