Javascript 从类的方法返回查询结果

Javascript 从类的方法返回查询结果,javascript,node.js,node-mysql,Javascript,Node.js,Node Mysql,我不知道这是否可行,因为我已经尽了最大努力,但仍然无法解决它。这是我的代码 class account {     constructor(id){         this.id = id;         this.solde = this.getSolde();     }       async getSolde(){         const result = await con.query('SELECT solde FROM

我不知道这是否可行,因为我已经尽了最大努力,但仍然无法解决它。这是我的代码

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];
        }
    }
当我调用getSolde时,我使用了我以前尝试过的不同方法,比如getter、callback,要么是未定义的,要么是挂起的promise,似乎都不适合我,有人能帮我吗

提前感谢

getSolde是异步的,所以您需要等待它。但是您不能在构造函数中这样做,因为它需要标记为异步,而这是无法完成的

由于您正在返回值,如果您只是在承诺上添加一个,则应返回该值:

constructor(id) {
    this.id = id;
    this.getSolde().then(result => this.solde = result);
}

建议避免在构造函数中执行异步操作。最好使用id实例化该类,然后从外部调用getSolde:


重复的我认为在异步函数外等待是不可能的,不管怎样,我已经尝试过并且没有使用wait account.getSolde^^^^^^^ SyntaxError:wait仅在异步函数中有效。很显然,为了等待另一个函数,您需要有一个异步函数。如果可能的话,请提供您的源代码,这样我们可以引导您进行更改。我在getSolde中得到promise undefinedIn,您可以console.logresult来确认您确实有一个数组结果,并且您想要的结果在索引0处。在getSolde中,我得到promise{}现在我设法在console上得到结果,console.logresult;但我不能将结果赋给任何变量,我只能在里面使用console.logmethod@user9224596您可以执行account.getSolde.thenresult=>account.solde=result;或者,如果还想注销结果,可以将其放在块中:account.getSolde.thenresult=>{console.logresult;result=account.solde;};
const account = new account(id: 1);
await account.getSolde();