menu

Questions & Answers

how to assign the result of a promise in a variable inside the constructor in typescript?

how to assign the result of a promise in a variable inside the constructor in typescript?

I'm using adonisjs to collect the data from the database. But it uses a promise to collect the information from the database.

How can I put the result in a variable?

I need this variable to be in the constructor.

Below is the code.

  private teste1: any
  private teste2: any

  constructor(protected ctx: HttpContextContract) {
    
   Database.from('estoquepas').then(res => {
     this.teste1 = res;
     console.log(res)
   })

    Estoquepas.findBy('siagreId', this.IDSiagre.siagreId).then(res => {
      this.teste2 = res;
      console.log(res)
    })


    console.log(this.teste1)
    console.log(this.teste2)
  }

What is inside the consule is shown, however the variable teste1 and teste2 does not display and is undefined.

Can anyone help with this question, thank you in advance for your attention.

Comments:
2023-01-19 23:10:04
You don't use a promise in the constructor. Load the data from the database before calling the constructor.
Answers(1) :

What you can do is create a static async method on your class and a dumb constructor which only assigns to values you give it (after the loading function does the async stuff):

class Something {
    constructor (
        protected ctx: HttpContextContract,
        private teste1: any,
        private teste2: any
    ) { }

    static async load(ctx: HttpContextContract) {
        const [ teste1, teste2 ] = await Promise.all[ Database.from('estoquepas'), Estoquepas.findBy('siagreId', IDSiagre.siagreId) ]

        return new this(ctx, teste1, teste2)
    }
}