0

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

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

1 Answer 1

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);
});
1
  • Or, you could just use pg-promise for that ;)
    – vitaly-t
    Commented Aug 2, 2015 at 0:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.