sqlite3 nodejs get value from table

12,659

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);
Share:
12,659
nolags
Author by

nolags

Updated on August 21, 2022

Comments

  • nolags
    nolags almost 2 years

    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!