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.

1

2 Answers 2

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() });
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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

2 Comments

I don't want to set the message here I want to set up a global variable ! Where I can save the content from the database.
I've edited the code. Does this answer your question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.