user1163466 user1163466 - 2 months ago 16
Node.js Question

Node JS - DB call async?

I am very new to node js , I used the following link to connect node js with postgres db:

How to make connection to Postgres via Node.js

The following code when ran in node console fetches some result from DB (Postgres)

var query_str = "SELECT name FROM city" ;
var pg = require('pg');
var conString = "postgres://postgres:postgres@localhost:5432/cfg";
var client = new pg.Client(conString);
client.connect();
var query = client.query(query_str);
console.log(query);


But when I put the above code inside function like this and make a function call

function getname()
{
var query_str = "SELECT name FROM city" ;
var pg = require('pg');
var conString = "postgres://postgres:postgres@localhost:5432/cfg";
var client = new pg.Client(conString);
client.connect();
var query = client.query(query_str);
console.log(query);
return query;
}


it returns a empty object. Is it because the code is asynchrnous? If so how can I solve the issue.

Can anyone help me in solve this issue. Or how to proceed further. Thanks.

Answer

client.query is asynchronous, your function should expect a callbackfunction or it should return a Promise

function getname(cb) {
  var query_str = "SELECT name FROM city";
  var pg = require('pg');
  var conString = "postgres://postgres:postgres@localhost:5432/cfg";
  var client = new pg.Client(conString);
  client.connect(function(err) {
    if (err) cb(err);
    client.query(query_str, function(err, result) {
      if (err) cb(err);
      cb(null, result);
      client.end(function(err) {
        if (err) cb(err);
      });
    });
  });
}

getname(function(error, data) {
  if (error) {
    console.log(error);
  } else {
    console.log(data);
  }
});

Comments