简体   繁体   English

将 node.js postgres 查询结果保存在变量中

[英]Saving node.js postgres query result inside a variable

I am trying to save some user_ids from my database in an array so that I can check against that array in a route.我正在尝试将数据库中的一些 user_ids 保存在一个数组中,以便我可以在路由中检查该数组。 The callback function logs the correct data but the value of the const stays undefined.回调函数记录了正确的数据,但 const 的值保持未定义。 Does anybody have any ideas on how to solve this problem?有没有人对如何解决这个问题有任何想法?

I am using the node-postgres library to connect to the database.我正在使用 node-postgres 库连接到数据库。

This is my code:这是我的代码:

database query function:数据库查询功能:

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 with callback function: const 带回调函数:

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

Any help is very much appreciated.很感谢任何形式的帮助。

What's happening in your console log is executing before your callback has completed.在您的回调完成之前,您的控制台日志中发生的事情正在执行。 To get this to work as you expect you want to refactor to use async/await or promises.要使其按预期工作,您需要重构以使用 async/await 或 promises。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM