I am trying to get data from a postresql database using async/await. the problem that I face is that the fetchMembers loads the data but it doesn't return that data, but only a blank object.
//server.js
const members = require('./memberDB')
app.get('/' , (req, res) => {
res.json(members)
console.log('Members: ',JSON.stringify(members))
})
//MemberDB.js
const fetchMembers = async function() {
const { Client, Pool } = require('pg')
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'whatevs',
password: '',
port: 5432,
})
const loadData = await pool.query('SELECT * FROM members;')
const data = await loadData.rows
console.log('data -> ', data)//I get this data correctly
return data // but I don't get the return value even if I remove 'await' from the 'loadData.rows'
}
module.exports.members = fetchMembers()
make fetchMembers returns a promise and await on it in the request handler.
const fetchMembers = async function() {
const { Client, Pool } = require('pg')
const pool = new Pool({
user: 'user',
host: 'localhost',
database: 'whatevs',
password: '',
port: 5432,
})
return pool.query('SELECT * FROM members;')
}
module.exports.members = fetchMembers;
in the route:
app.get('/' , async (req, res) => {
const loadData = await fetchMembers();
const data = loadData.rows;
res.json(data);
})
The problem was you call fetchMembers and await on the promise inside it but that do not block the code. the execution of the req handler continue and the members was not resolved yet. So you have two solution either to await in fetchMembers and the request handler or return a promise and await only in the request handler. Like Paul said it is better to export the function itself.