Reputation: 111
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);
Upvotes: 10
Views: 21214
Reputation: 423
This is what you are looking for:
async function selectFrom(data, table, condition) {
try {
const res = await pool.query(
`SELECT ${data} FROM ${table} ${condition}`
);
return res.rows[0][data];
} catch (err) {
return err.stack;
}
}
Outside of the previous function:
async function whateverFuncName () {
var result = await selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`);
console.log(result);
}
EDIT: I didn't run this code snippet but the main concept is pretty straightforward.
Upvotes: 10
Reputation: 971
The "query" method is an async call, you should use async/await or Promise.
With async/await:
await client.connect()
const res = await client.query("SELECT amount FROM total_nonfarm_monthly_sa WHERE month='2019-08-31'");
console.log(res.rows[0]);
await client.end();
Edit: I can see that there's an option of callback, but I would use the async/await
Upvotes: 4
Reputation: 5704
You need to use callbacks:
var selectFrom = function(data, table, condition, callback) {
pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
if(err)
return callback(err);
callback(null, result.rows[0][data]);
})
pool.end();
}
selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`, function(err, result){
console.log(err, result);
});
or promises:
var selectFrom = function(data, table, condition) {
return new Promise(function(resolve, reject){
pool.query(`SELECT ${data} FROM ${table} ${condition}`, function(err, result) {
if(err)
return reject(err);
resolve(result.rows[0][data]);
})
pool.end();
});
}
selectFrom('amount','total_nonfarm_monthly_sa', `WHERE month='2019-08-31'`)
.then(function(result){
console.log(result);
}).catch(function(err){
console.log(err);
});
Upvotes: 1