I am new to node.js, and currently working on demo project so my requirement is to get count of userId which I am calling by function and this function is declared outside of route, but I am getting undefined but in same function getting count values but when I returned count still getting undefined in route.
Code:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
const usersQuery = "SELECT * FROM users";
dbConn.query(usersQuery,function(err,rows) {
if(err) {
console.log('this error',res);
} else {
let total=getCount(); // calling function placed outside
console.log(total);
}
});
});
Function declared outside to return count:
function getCount(){
const usersQuery = "SELECT count(id) as cnt FROM users";
dbConn.query(usersQuery,function(err,rows) {
if(err) {
console.log('failed to get count');
} else {
return rows; // retun count
}
})
}