Asynchronous __在Typescript中使用async/await时未定义等待器
我在Typescript中有以下代码片段:Asynchronous __在Typescript中使用async/await时未定义等待器,asynchronous,typescript,async-await,Asynchronous,Typescript,Async Await,我在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: { n
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)并运行时,我得到以下错误:
未捕获引用错误:\未定义等待器
这意味着什么?我如何获得预期的功能
更新:
当您使用将来版本的JavaScript(ES6及更高版本)中的某些功能时,如您的案例中的
async/await
,TypeScript
会生成帮助函数。这些助手函数用于提供新功能,如ES5代码,因此可以在web浏览器中运行
您的问题:
在tsconfig.json
中,将noEmitHelpers
值设置为true
。通过这样做,您可以告诉TypeScript
编译器您将自己提供这些助手函数
如何修复它:
- 您可以在
中将tsconfig.json
值设置为noEmitHelpers
,这样false
编译器将在需要时发出helper函数。此方法的一个缺点是,如果您在两个不同的文件中使用例如TypeScript
,则助手函数将发出2次(每个文件一次)async/await
- 另一种解决方案是在使用
时设置tsc
标志。它将告诉--importpers
编译器只包含一次helper函数。请注意,如果使用此解决方案,则必须安装TypeScript
软件包tslib
在您的情况下:
tsc--importpers-w
您能分享您的tsconfig.json
?您用来编译代码的命令。@Romain-Sure-是tsconfig,我使用根目录中的tsconfig运行此命令。tsc-w
。如果发布的答案解决了您的问题,请将其标记为已接受
{
"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"
]
}