I am attempting to return the result of a node-postgres query and store it in a variable. I can manage a console.log just fine, but cannot find a way to return the result so that it is accessible outside of the query method. I'm at a loss, and know I must be missing something obvious (or multiple obvious things), because if it isn't possible to do this I don't understand the point of node-postgres since all I will ever be able to do is log my results to the console.
I have tried the code below, along with a version using promises, and both receive the same result, 'undefined.' A console.log within the else works fine, but a return does not make the result accessible to the rest of the function. In the code below, my return comes back as 'undefined' as would a console.log in its place.
var selectFrom = function(data, table, condition) {
var queryResult;
pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
if(err) { console.log(err); }
else { queryResult = result.rows[0][data]; }
})
pool.end();
return queryResult;
}
var result = selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
console.log(result);
return queryResult
returns before query is done. You have to somehow wait for the results to come from DB, before returning them. Read about async/await or maybe return a Promise that's resolved with result from the DB. – ahwayakchih