nolags
nolags

Reputation: 633

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

Can anyone help me? Thanks in advance.

Upvotes: 1

Views: 118

Answers (2)

AshanPerera
AshanPerera

Reputation: 628

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})
    }
})

Upvotes: 1

Simon
Simon

Reputation: 1536

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() });
    }
});

Upvotes: 2

Related Questions