首页 > 解决方案 > 如何在构造函数中等待?

问题描述

我尝试在类构造函数中使用 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)
  }
}

标签: javascriptnode.jstypescript

解决方案


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)
  }
}

也许你可以这样做。


推荐阅读