nolags nolags - 1 year ago 74
Node.js Question

nodejs synchronous call: getting db callback and parse it to frontend

In my NodeJS backend I have a function where I get a value from the sqlite database and I want to send it to the frontend but it always says

Object { msg: false }
i think I need a function where I can make a synchronous call of the functions.
My Code:

router.get('/', function(req, res, err){
var msg = " ";
var uid = req.session.user;

function printMsg(message){
msg = message;
db.getMsg(uid, printMsg);
res.send({msg : "No message available"});
} else{
res.send({msg: msg})

Can anyone help me? Thanks in advance.

Answer Source

i assume db.getMsg is your own code which will throw error if hit error and return message in callback if success

  router.get('/', function(req, res, err){
    try {
      var uid = req.session.user; 

      db.getMsg(uid, function(msg) {
        if (msg) res.send({msg: msg})
        else res.send({msg : "No message available"});
    } catch (error) {
      res.send({error: error.toString() });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download