Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await in constructor? [duplicate]

I try to use await in class constructor but failed, here are my trys:

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)
  }
}
like image 628
DaveICS Avatar asked Dec 11 '25 18:12

DaveICS


1 Answers

You can only use await inside an async function, so either extract the code to an async method or use a immediately-invoked async function expression.

constructor(private readonly db: EntityManager){
    (async()=>{
        await mydb.insert(god)
        await mydb.insert(human)
        await mydb.insert(city)
    })();
}
like image 138
Unmitigated Avatar answered Dec 14 '25 10:12

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!