从类的方法返回查询结果

问题描述 投票:0回答:2

我不知道是否可行,因为我已经尽力而为,但仍然无法解决,这是我的代码

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()时,我已经使用我之前尝试过的其他方法进行了未定义或待定的promise,例如getter,callback,似乎没有一种对我有用,有人可以帮我吗

预先感谢

javascript node.js node-mysql
2个回答
0
投票

getSolde()是异步的,因此您需要等待它。但是您不能在构造函数中执行此操作,因为它需要被标记为异步,这无法完成。

由于您正在返回值,因此,如果仅在promise上添加then,则应返回它:

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

0
投票

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

const account = new account(id: 1);
await account.getSolde();
© www.soinside.com 2019 - 2024. All rights reserved.