node.js - sqlite3 nodejs get value from table -


i've got function getname in db.js

function getname(uid){     db.all("select name table uid = ? ",  function (err){         if(err){             console.log(err);         }else{             console.log(this);         }     }); } 

and want name , save var name in file.

var uid = req.session.user;   var name = db.getname(uid);       console.log(name); 

what wrong db function getname why undefined? great if me!

returning data async function might return undefined database request might not have completed on execution of return statement.

function getname(uid, callback){   var query = "select name table uid = " + uid;   var name = null;   db.all(query, function (err, rows) {     if(err){         console.log(err);     }else{       name = rows[0].name;     }   });   return name; <--- can execute before db.all() if executed therefore returning null. because javascript runs asynchronously. } 

the result database query needs passed in callback or can saved in global variable.

function getname(uid, callback){   var query = "select name table uid = " + uid;   db.all(query, function (err, rows) {     if(err){         console.log(err);     }else{         callback(rows[0].name);     }   }); } 

in order execute file:

function print(name) {   console.log(name); } var uid = req.session.user; getname(uid, print); 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -