4

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!

nolags
  • 583
  • 1
  • 4
  • 23

1 Answers1

4

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);
Himani Agrawal
  • 1,166
  • 11
  • 14
  • How can I access the name outside the function print? – nolags Sep 28 '16 at 06:54
  • declare a global variable username outside print function. var username = ''; In print function do: username = name; As getName is async function accessing username before async completes will result in username set to ''. – Himani Agrawal Sep 28 '16 at 07:02
  • It doesn't overwrite the username variable. When I log the username it's empty! Just how I defined it in the global variable. – nolags Sep 28 '16 at 07:20
  • You are accessing the variable before getName finishes its execution. Trying printing the username after setting it to name. – Himani Agrawal Sep 28 '16 at 07:35
  • Wrote console.log(username) after the getName function, but it still calls the log before the print function..? – nolags Sep 28 '16 at 07:49
  • yes, console.log(username) after getName is executed before getName is executed. write console.log(username) in print function after username = name; – Himani Agrawal Sep 28 '16 at 08:00
  • But how can I use the variable username then outter the function? – nolags Sep 28 '16 at 08:03