Can someone show me an example of passing the results of a postgres query in Nodejs to another function?
Asked
Active
Viewed 3,055 times
0
-
1I'm sure [google](https://google.com) can. – zerkms Jul 06 '15 at 00:54
-
Request the result as a promise, with [pg-promise](https://github.com/vitaly-t/pg-promise), and then pass the returned promise into your function. – vitaly-t Aug 02 '15 at 00:32
1 Answers
1
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);
});

Shimon Brandsdorfer
- 1,673
- 9
- 23
-
Or, you could just use [pg-promise](https://github.com/vitaly-t/pg-promise) for that ;) – vitaly-t Aug 02 '15 at 00:29