I am running a simple program for long polling to check if any change happens in database to send it to browser in Node.js. I know how to use the callback function but I need to return a value from program.query function to be returned because I will use it in the recursive function. Thanks for your help.
var server=http.createServer(function(req,res){
program.run(res, 5);
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(9000);
var program = {
run: function(res, id, old){
if(old == undefined){
// I need a value from database to be returned to old variable
old = program.query(res, id /*, function(){res.end('there') }*/);
}
clearTimeout(tt);
var tt = setTimeout( function(){
// I need a value from database to be returned to new_ variable
var new_ = program.query(res, id /*, function(){res.end('there') }*/);
if(new_ != old){
// ... Send Response with the change to browser
}
else{ // no change in database, so run again
old = new_;
program.run(res, id, old);
}
}, 2000);
},
query: function(res, id /*,callback*/){
connection.query('SELECT table1.column1 FROM table1 WHERE table1.id ="'+id+'"', function(err, rows, fields){
//callback(res,id,rows[0].column1); // I don't want this solution
return rows[0].column1; // Not working..
});
}
};