Can someone show me an example of passing the results of a postgres query in Nodejs to another function?
1 Answer
I have a config.json
file, where I store my configurations.
var pg = require('pg')
,q = require('q')
,config = require('custom-modules/config.json')
conString = 'postgres://'+ config.pg.admun +':' + config.pg.admpw + '@' + config.pg.host + ':' + config.pg.port + '/' + config.pg.defdb;
function runSQL (sqlStatement) {
var deferred = q.defer();
var results = [];
// Get a Postgres client from the connection pool
pg.connect(conString, function(err, client, done) {
// SQL Query > Select Data
var query = client.query(sqlStatement, function(err, res) {
if(err) console.log(err);
deferred.resolve(res);
});
// After all data is returned, close connection and return results
query.on('end', function() {
client.end();
deferred.resolve(results);
});
// Handle Errors
if(err) {
console.log(err);
}
});
return deferred.promise;
};
now you can run the function like this:
runSQL("SELECT * FROM tablename").then(function(res) {
// here you have access to the result of the query... with "res".
console.log(res);
});