Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

Can someone show me an example of passing the results of a postgres query in Nodejs to another function?

share|improve this question

marked as duplicate by zerkms, Alexei Levenkov, MarsAtomic, Adrian Cid Almaguer, Mike Laren Jul 6 '15 at 2:29

This question was marked as an exact duplicate of an existing question.

1  
I'm sure google can. – zerkms Jul 6 '15 at 0:54
    
Request the result as a promise, with pg-promise, and then pass the returned promise into your function. – vitaly-t Aug 2 '15 at 0:32

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);
});
share|improve this answer
    
Or, you could just use pg-promise for that ;) – vitaly-t Aug 2 '15 at 0:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.