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!

3
  • you are returning value from a async function Commented Sep 22, 2016 at 12:50
  • @CodeBean do I have to make a db.get request ? or how can I get the name from the database? Commented Sep 22, 2016 at 12:51
  • i think this will help : github.com/mapbox/node-sqlite3/blob/master/examples/… Commented Sep 22, 2016 at 12:55

1 Answer 1

5

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

7 Comments

How can I access the name outside the function print?
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 ''.
It doesn't overwrite the username variable. When I log the username it's empty! Just how I defined it in the global variable.
You are accessing the variable before getName finishes its execution. Trying printing the username after setting it to name.
But how can I use the variable username then outter the function?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.