0

I don’t know if this is possible, since i've do my best and still can’t resolve it here's my code

class account {
        constructor(id){
            this.id = id;
            this.solde = this.getSolde();
        }
     
        async getSolde(){
            const result = await con.query('SELECT solde FROM account WHERE id = ?', [this.id])
            return result[0];
        }
    }

When I call getSolde() I’ve either undefined or pending promise with different methods I've tried before, like getter, callback, none seems to work for me, can anyone help me

Thanks in advance

2 Answers2

0

getSolde() is async so you need to await it. But you can't do that inside the constructor because it needs to be marked as async, which can't be done.

Since you are returning the value, it should be returned if you just add a then on the promise:

constructor(id) {
    this.id = id;
    this.getSolde().then(result => this.solde = result);
}
Shahzad
  • 2,033
  • 1
  • 16
  • 23
  • i'm getting promise undefined – user9224596 Dec 31 '19 at 19:01
  • In `getSolde`, can you console.log(result) to confirm that you actually have a result which is an array and the result you want is at index 0. – Shahzad Dec 31 '19 at 19:05
  • in getSolde i'm getting Promise { } – user9224596 Jan 01 '20 at 20:17
  • now i managed to get result on console, with < const account = new acount(id); account.getSolde().then(result =>console.log(result)); but i can't assignt result to any variable, i can only console.log inside then method – user9224596 Jan 02 '20 at 23:05
  • @user9224596 you can do `account.getSolde().then(result => account.solde = result);` Or if you want to log out the result as well, you can put it inside a block: `account.getSolde().then(result => {console.log(result); result = account.solde;});` – Shahzad Jan 03 '20 at 11:29
  • how could I call account.solde if this isn't defined inside constructor ? – user9224596 Jan 03 '20 at 13:24
  • Maybe this will help you understand: `const a = new account(1); a.getSolde().then(result => a.solde = result).then(_ => console.log(a.solde));` – Shahzad Jan 03 '20 at 14:18
0

It is recommended to avoid asynchronous actions inside your constructor. It would be better to instantiate the class with using id and then externally call getSolde():

const account = new account(id: 1);
await account.getSolde();
Daniel Stoyanoff
  • 1,443
  • 1
  • 9
  • 25