2

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)
  }
}
Andy
  • 61,948
  • 13
  • 68
  • 95
DaveICS
  • 37
  • 2
  • 6

2 Answers2

1

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)
    })();
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    One thing to note, if anything in the constructor relies upon data returned by an `async` call, that code must also be inside the immediately-invoked function expression (IIFE). Attempting to pass a value outside the IIFE will return a promise, continuing the initial problem. – Zarepheth May 08 '23 at 15:05
-1

Try call to constructor from outside

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