【问题标题】:Returning a query result from a class's method从类的方法返回查询结果
【发布时间】:2019-12-31 11:11:04
【问题描述】:

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

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)未定义或待处理的承诺,似乎没有一个对我有用,谁能帮助我

提前致谢

【问题讨论】:

标签: javascript node.js node-mysql


【解决方案1】:

getSolde() 是异步的,所以你需要等待它。但是你不能在构造函数内部这样做,因为它需要被标记为异步,这是无法做到的。

由于您要返回值,因此如果您只是在 promise 上添加 then,则应该返回它:

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

【讨论】:

  • 我得到了未定义的承诺
  • getSolde 中,您能否通过console.log(result) 确认您实际上有一个结果是一个数组并且您想要的结果在索引0 处。
  • 在 getSolde 我得到了 Promise { }
  • 现在我设法在控制台上得到了结果,console.log(result));但我不能将结果分配给任何变量,我只能在 then 方法中使用 console.log
  • @user9224596 你可以做account.getSolde().then(result => account.solde = result); 或者如果你也想注销结果,你可以把它放在一个块里:account.getSolde().then(result => {console.log(result); result = account.solde;});
【解决方案2】:

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

const account = new account(id: 1);
await account.getSolde();

【讨论】:

  • 我认为不可能在异步函数之外等待,无论如何我已经尝试过但没有工作
  • await account.getSolde() ^^^^^ SyntaxError: await is only valid in async function
  • 好吧,显然你需要一个异步函数来等待另一个函数。如果可能,请提供您的源代码,以便我们指导您更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2018-10-14
  • 2022-01-15
  • 2013-08-24
  • 2013-10-01
相关资源
最近更新 更多