0

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
  • 53,323
  • 11
  • 64
  • 89
DaveICS
  • 17
  • 5

3 Answers3

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

maybe you can do like this.

kyun
  • 8,693
  • 8
  • 27
  • 56
  • 1
    this.init(db) inside constructor – Bipin Shrestha Aug 10 '21 at 04:02
  • 1
    I think this is an anti-pattern in many cases because the constructor will return immediately, which could be leaving the object in an invalid state for some other code to use. I'd instead use a static function that awaits all the necessary values and returns `Promise`. – Mack Aug 10 '21 at 05:31
0

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
  • 46,070
  • 7
  • 44
  • 60
-1

Try call to constructor from outside

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