javascript - 如何在构造函数中等待?
问题描述
我尝试在类构造函数中使用 await 但失败了,这是我的尝试:
export class TheHistory {
constructor(private readonly db: EntityManager){
//try1: too many levels !!! try use await
mydb.insert(god).then(() => {
mydb.insert(human).then(() => {
mydb.insert(city).then(() => {
//.....
})
})
})
//try2: ERROR -- 'await'expressions are only allowed within async functions and at the top levels of modules
await mydb.insert(god)
await mydb.insert(human)
await mydb.insert(city)
}
}
解决方案
export class TheHistory {
constructor(private readonly db: EntityManager){
this.init(db);
}
async init(mydb){
await mydb.insert(god)
await mydb.insert(human)
await mydb.insert(city)
}
}
也许你可以这样做。
推荐阅读
- javascript - 在数据表中省略而不是包含来自搜索的匹配结果
- vb.net - 数组越界错误 Visual basic forms
- javascript - AFrame / AR.js 定位 - 无法改变 X 轴
- python-3.x - 在 django 中加载静态文件后看不到 css 工作
- sql - 如何解决 ORA-01843: not a valid month eror
- google-cloud-platform - 全局地址不支持标准网络层
- reactjs - 'beforeinstallprompt' 的正确类型是什么
- hibernate - 如何在@Embeddable 中使用@GeneratedValue 作为复合主键?
- python - 如何使用 Selenium 动态更改 Firefox 无头模式?
- python - 如何从两个列表中删除相同的单词?