0

I am completely new in Node.js and i do not know how to call or use a function in Node.js. I created one function connectWithDatabase() and i want to check if it fetch data from table and returns value.

This code works fine if i will add this function code router.get('/', function(req, res) BUT if i will create a function connectWithDatabase() and try to call it, this function will return 0. value= result.rows.length; does not assign value, I am have no idea how to fix this and how to create a "callback" function. Kindly help...

var connectWithDatabase = function(){

    var conString = databasehelper.conString;
    console.log(conString);
    var client = new pg.Client(conString);
    var value = 0;

    pg.connect(conString, function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query("SELECT * FROM users", function(err, result) {

            if(err) {
                return console.error('error running query', err);
            }

            console.log(result.rows);
            value= result.rows.length;
            console.log("result.rows.length " + result.rows.length);
            client.end();
            done();
            //output: 1
        });
    });

    console.log("value " + value);
    return value;
}

/* GET home page. */
router.get('/', function(req, res) {

    var value = connectWithDatabase();
    console.log("value " + value);
    res.render('index');
});
user3173811
  • 43
  • 1
  • 4
  • Your operation is asynchronous. Thus, the result happens long after your function has returned. So, you can't call the function and have it return a result. Instead, you must pass in a callback and have the function call the callback with the result when the result is available or return a promise and resolve the promise when the result is done. To understand more about this, read the answers this has been marked a duplicate of. – jfriend00 Jun 04 '15 at 21:10
  • FYI, this issue has nothing to do with node.js specifically and everything to do with any asynchronous operation in Javascript so discussion of returning values from Ajax calls in the browser is the exact same issue. – jfriend00 Jun 04 '15 at 21:11

0 Answers0