简体   繁体   中英

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. The callback function logs the correct data but the value of the const stays undefined. Does anybody have any ideas on how to solve this problem?

I am using the node-postgres library to connect to the database.

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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