Reputation: 633
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
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
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