gor*_*tde 1 async-await typescript nestjs
@Injectable()
export class MyService {
...
constructor(@Inject('CONFIG') private config:ConfigOptions){
this.connection= // await initConnection(config); <-- this returns a promise! How to await this?
}
send(payload:string){
this.connection.send(payload)
}
}
Run Code Online (Sandbox Code Playgroud)
如何await异步调用以initConnection()确保服务在使用前已初始化?
构造函数不能有异步代码,JavaScript 就是这样。相反,您可以做的是使用挂钩onModuleInit并等待那里的连接,或者采用您拥有的提供程序并通过自定义提供程序CONFIG创建一个提供程序,该提供程序可以具有. 就像是CONNECTIONuseFactoryawait
{
provide: 'CONNECTION',
inject: ['CONFIG'],
useFactory: async (config: ConfigOptions) => {
return await initConnection(config);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
374 次 |
| 最近记录: |