I'm new to Node... I have a module that connects to a postgres DB through pg-node. I have no problem with that. My problem is that when calling that module, from another module, and then wanting to use the data that came out of the DB, it tells me undefined... I'm almost sure it's because the connection to the DB returns a promise, and the data doesn't They are available when you use them. I paste code
PG connection module
module.exports = function (query) {
const { Client } = require ('pg')
const connection = {
user: 'postgres',
host: 'localhost',
database : 'hoteltest',
password: '1234',
port: 5432
}
const client = new Client(connection)
var datos;
client.connect()
client.query(query)
.then (response => {
datos = response.rows
console.log(datos)
return datos
client.end()
})
.catch(err => {
console.log(err)
client.end()
})
}
and so I call this module:
import data from './pg/index.js'
var pgdata;
pgdata = data('SELECT * FROM usuarios')
console.log(pgdata)
Any suggestions? Thank you!
Although you have solved it, I tell you that you only needed to return the promise of the PG module, I will show you what I mean:
And remember that you return a promise, therefore:
I hope that with this example I have helped you to understand Promises a bit, you can also solve it with Async/Await and Promise, search the internet to find many examples, if not ask.
Cheers