网站搜索

javascript - 如何在构造函数中使用 await?


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

答案#1

你只能在 async 函数内部使用 await,所以要么将代码提取到一个 async 方法中,要么使用立即调用的异步函数表达式。

constructor(private readonly db: EntityManager){
    (async()=>{
        await mydb.insert(god)
        await mydb.insert(human)
        await mydb.insert(city)
    })();
}

答案#2

尝试从外部调用构造函数

async function foo () {
    var myObj = await mydb.insert(god);
}