0

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 :)

Porridge
  • 3
  • 1
  • Did my post below answer your question? If not then please comment so I'll try to clarify. – rsp Sep 30 '16 at 13:43
  • Oh yes it did answer my question. I didn't still get the hang of it but I'll get there. I solved the problem in python (it was an exercise) and am planning to read more into it once I'm out of deadlines ;-) – Porridge Oct 04 '16 at 19:56

2 Answers2

0

You did not call the getValue function. Call it like this: getValue(). But that function returns null.

You will need to start with a more basic example. First learn about function calls, then when you have that down move on to other things.

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31
0

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:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177