节点从数据库查询回调到快速请求

时间:2016-11-30 09:41:14

标签: javascript node.js express sqlite callback

我希望下面的函数(listServers())回调数据,以便在下面的快速请求中使用。但是我对回调的设置感到困惑,因为我从搜索中得到了相互矛盾的信息。

服务器运行listServers很好,但在将值返回给请求时似乎超时。

我在服务器上请求/的输出是:

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

代码:

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);
});
});

完整代码为here

1 个答案:

答案 0 :(得分:0)

你传递给listServers()的是一个回调函数,所以你不应该在listServers()中返回数据/抛出错误,而应该调用该回调并将错误或数据传递给它: / p>

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);
    });
});