Reputation: 633
I've got the function getName in my db.js
function getName(uid){
db.all("SELECT name FROM table WHERE uid = ? ", function (err){
if(err){
console.log(err);
}else{
console.log(this);
}
});
}
and I want to get the name and save it to var name in another file.
var uid = req.session.user;
var name = db.getName(uid);
console.log(name);
what is wrong about the db function getname why do I get undefined? Would be great if you could help me!
Upvotes: 4
Views: 18211
Reputation: 1272
Returning data from an async function might return undefined as the database request might not have completed on execution of return statement.
function getName(uid, callback){
var query = "SELECT name FROM table WHERE uid = " + uid;
var name = null;
db.all(query, function (err, rows) {
if(err){
console.log(err);
}else{
name = rows[0].name;
}
});
return name; <--- this can be execute before db.all() if executed therefore returning null. This is because javascript runs asynchronously.
}
The result from database query needs to be passed in a callback or it can be saved in a global variable.
function getName(uid, callback){
var query = "SELECT name FROM table WHERE uid = " + uid;
db.all(query, function (err, rows) {
if(err){
console.log(err);
}else{
callback(rows[0].name);
}
});
}
In order to execute from another file:
function print(name) {
console.log(name);
}
var uid = req.session.user;
getName(uid, print);
Upvotes: 5