How can I proprely return the data I want from a postgre query ?
function getTableName() {
let queryTableName = `SELECT * FROM admin.information_schema.tables;`;
let response;
client.query(queryTableName).then(res => {
let names = Array();
for (let i = 0; i < res.rowCount; i++) {
names.push(res.rows[i]['table_name']);
}
response = names;
}).catch(err => {
console.error(err);
});
return response;
}
Your code returns the response synchronously, before the query result has arrived from the database asynchronously. Therefore what you return is still undefined.
You must either convert getTableName into an asynchronous function, or implement an express middleware, which is by nature asynchronous:
app.get("/path", function(req, res, next) {
let queryTableName = `SELECT * FROM admin.information_schema.tables;`;
client.query(queryTableName).then(resp => {
let names = Array();
for (let i = 0; i < resp.rowCount; i++) {
names.push(resp.rows[i]['table_name']);
}
res.json(names);
}).catch(err => {
console.error(err);
next(err);
});
});