I am trying to fetch the number of records from Database using nodejs but the problem is that due to sync requests , I am not able to print them. When I try to print it inside the function , it prints fine but outside the function , it doesn't. I know it is due to sync behavior of JS but I want to do this (may be asynchronsly) . I am very new to Javascript and nodejs , so please guide me how can I do this. here is the code.
router.post('/numofrecs', function(req, res) {
var db = new Db('nmydb', new Server('localhost', '27017'));
db.open(function (err, db) {
db.authenticate('', '', function (err, result) {
var url = 'mongodb://localhost:27017/nmydb';
client.connect(url, function (err, db) {
que = new Array();
var questioncol = db.collection('allquestions');
questioncol.find({}).count(function (err, data) {
rec = data;
console.log("Num of rec:"+rec);
//inside the connect function , it prints fine here
});
console.log('Num of rec:'+ rec);
//but it doesnot print here outside the connect function and just print "undefined"
Since you are building an HTTP server, you do not want to have any synchronous actions on your server because such actions would result in your server becoming unresponsive to all clients during the synchronous action. Instead, you should do the work you need within the callback of the db query.
router.post('/numofrecs', function(req, res) {
var db = new Db('nmydb', new Server('localhost', '27017'));
db.open(function (err, db) {
db.authenticate('', '', function (err, result) {
var url = 'mongodb://localhost:27017/nmydb';
client.connect(url, function (err, db) {
var que = new Array();
var questioncol = db.collection('allquestions');
questioncol.find({}).count(function (err, data) {
console.log("Num of rec:"+data);
// do stuff with data here.
doStuff(data);
});
});
});
});
});
Don't forget to var
your variables.
npm install -g xd-synchttp
const sync = require('xd-synchttp');
let content = "";
let post_data={'a':1,'b':2};
try{
content = sync.http_get('http://www.csdn.net',3);
console.log(sync.http_post('http://www.baidu.com',post_data,0));
}
catch(err){
console.log(err);
}