javascript - ¿Cómo usar await en el constructor?
Intenté usar await en el constructor de la clase, pero fallé, aquí están mis intentos:
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)
}
}
Respuesta #1
Solo puedes usar await dentro de una función async, así que extrae el código a un método async o usa una expresión de función async inmediatamente invocada.
constructor(private readonly db: EntityManager){
(async()=>{
await mydb.insert(god)
await mydb.insert(human)
await mydb.insert(city)
})();
}
Respuesta #2
Intentar llamar al constructor desde fuera
async function foo () {
var myObj = await mydb.insert(god);
}
