1

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);
    if(err){
             res.send({msg : "No message available"});
         } else{
             res.send({msg: msg})
         }
});

Can anyone help me? Thanks in advance.

nolags
  • 633
  • 1
  • 11
  • 30
  • Duplicate: http://stackoverflow.com/questions/6898779/how-to-write-asynchronous-functions-for-node-js – iKoala Nov 25 '16 at 07:08

2 Answers2

2

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() });
    }
});
Simon
  • 1,426
  • 3
  • 16
  • 24
  • How can I save the msg into a global variable ? Cause I want to edit msg, which now only works in the db.get function.. But i want to edit it outside the db.get function. – nolags Nov 25 '16 at 07:43
  • Try not to set your anything in global variable, i suggest you do it by db.setMsg(newMsg) and retrieve it using same db.getMsg – Simon Nov 26 '16 at 23:52
1

Your db.getMsg() function should be defined as follows

function getMsg(uid, callback){
// your logic
var resultFromDb = ''; // Contents from db.

 if( not success ){  // If that fails
    err = //define error object
    callback(err)   // Call the callback function only with an error.
 }
 else{
    callback(undefined, resultFromDb ) // else, call the callback function with an 
                             // undefined value for the error.    
  }
}

And when you call db.getMsg(), call it as follows

db.getMsg(uid, function(err, result) {
    if(err){
        res.send({msg : "No message available"});
    }else{
        msg = result
        res.send({msg: result})
    }
})
AshanPerera
  • 596
  • 1
  • 7
  • 18