Q:

Store database attribute in var

I have the following code:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('test.db');

db.serialize(function() {
    db.run("CREATE TABLE IF NOT EXISTS counts (key TEXT, value INTEGER)");
    db.run("INSERT INTO counts (key, value) VALUES (?, ?)", "counter", 0);
});

var getValue = function(res){
    db.get("SELECT value FROM counts", function(err, row){
        res.json({ "count" : row.value });
        return;
    });
};

console.log(getValue);

Output is
[Function]

But should be json. What am I doing wrong?
I took the example from http://dalelane.co.uk/blog/?p=3152
Thanks in advance :)

A:

Of course getValue is a function, because few lines before you wrote:
var getValue = function(res){
   // ...
};

so now, when you write:
console.log(getValue);

it tells you that it's a function.
What you probably want is:
getValue({json: console.log});

or maybe:
getValue({json: data => console.log(data.count)});

if you want to display that value from an object passed to res.json, if you have a db.get() function that returns one row in that format - make sure that you're using it correctly in the first place. But keep in mind that this is asynchronous so you won't be able to store it in a variable immediately.
Simplifying your example a little bit, you can do:
asyncFunc('args', function (err, data) {
  if (err) {
    console.log('Error:', err);
  } else {
    console.log('Value:', data);
  }
});

but you won't be able to return that value, because returning a simple value is a synchronous process. What you can return is a promise:
function getPromise() {
  return new Promise(function (resolve, reject) {
    asyncFunc('args', function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

that you can then use like this:
getPromise()
  .then(value => console.log('Value:', value))
  .catch(error => console.log('Error:', error));

If you don't know why is that then you can see some other answers where I explain how to get data from asynchronous function calls which you may find helpful:

A detailed explanation on how to use callbacks and promises
Explanation on how to use promises in complex request handlers
An explanation of what a promise really is, on the example of AJAX requests
An explanation on how to handle errors in callbacks and promises

