【问题标题】:Saving node.js postgres query result inside a variable将 node.js postgres 查询结果保存在变量中
【发布时间】:2020-06-13 02:51:46
【问题描述】:

我正在尝试将数据库中的一些 user_ids 保存在一个数组中,以便我可以在路由中检查该数组。回调函数记录正确的数据,但 const 的值未定义。有人对如何解决这个问题有任何想法吗?

我正在使用 node-postgres 库来连接数据库。

这是我的代码:

数据库查询功能:

const getAll = (callback) => {
  const query = `SELECT user_id FROM users`;

  pool
    .query(query)
    .then(data => {
      callback(null,data.rows)
    })
    .catch(e => console.error(e.stack))
}

带有回调函数的常量:

const users = db.getAll(function(err,data) {
  if (err) {
    console.log(err);            
  } else {            
    const ids = data.map(x => x.user_id)
    console.log(ids);  // logs an array of ids 
    return ids         
  }    
})

console.log(users) // returns undefined

非常感谢任何帮助。

【问题讨论】:

  • @xvii 是的,肯定需要检查 db.getAll 库描述

标签: javascript node.js database postgresql node-postgres


【解决方案1】:

您的控制台日志中发生的事情在您的回调完成之前执行。要使其按预期工作,您需要重构以使用 async/await 或 Promise。

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多