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