bertie.io bertie.io - 10 days ago 6
Javascript Question

Node Callback from database query to express request

I want the function below (listServers()) to callback data to be used in the express request below. But I am confused by the set up of a callback as I have got conflicting information from searching.

The server runs listServers fine but seems to timeout when returning the value to the request.

The output from me requesting / on the server is:

forEach length:1
forEach length:2
listServers length:2
::ffff:*IP* - - [30/Nov/2016:09:31:19 +0000] "GET / HTTP/1.1" - -


Code:

var listServers = function (err, data) {
var list=[];
db.all("SELECT * FROM Servers;", function(err, rows){
rows.forEach(function(e){
var confi = fs.readFileSync(paths.factorioDir + "server" + e.serverID + paths.conf);
var conf = JSON.parse(confi);
var item = {id: e.serverID, conf:conf};
list.push(item);
console.log("forEach length:" + list.length);
});
if (err) throw err;
console.log("listServers length:" + list.length);
data = list;
return data;
});

};

admin.get('/', function(req, res) {
listServers(function(err, data){
console.log(data.length);
servers = data;
console.log("/ servers length"+ servers.length);
var adminTemplate = pug.compileFile(__dirname + '/template.pug');
var context = { servers: servers };
var html = adminTemplate(context);
res.send(html);
});
});


Full code is here

Answer

What you are passing to listServers() is a callback function, so instead of returning the data/throwing an error in listServers() you should invoke that callback and pass it either the error or the data:

var listServers = function (callback) {
    var list=[];
    db.all("SELECT * FROM Servers;", function(err, rows){
        if (err) {
            callback(err, []);

            return;
        }

        rows.forEach(function(e){
            var confi = fs.readFileSync(paths.factorioDir + "server" + e.serverID + paths.conf);
            var conf = JSON.parse(confi);
            var item = {id: e.serverID, conf:conf};
            list.push(item);
            console.log("forEach length:" + list.length);
        });

        console.log("listServers length:" + list.length);
        callback(null, list);
    });
};

admin.get('/', function(req, res) {
    listServers(function(err, data){
        if (err) {
            // Handle error
        }

        console.log(data.length);
        servers = data;
        console.log("/ servers length"+ servers.length);
        var adminTemplate = pug.compileFile(__dirname + '/template.pug');
        var context = { servers: servers };
        var html = adminTemplate(context);
        res.send(html);
    });
});