node的模块函数返回值为空/未定义?

时间:2016-10-15 17:50:56

标签: node.js sqlite

我正在尝试从基于slqLite的记录器返回html编码的表行值。因为我是节点模块的新手,所以我坚持:

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
var html = '';

module.exports = {
  readHtml: function() { 
    var html = ''; // optional but does not work here as well
    db.serialize(function() {
      db.each("SELECT rowid AS id, info FROM logger", function(err, row) {
        html = html + '<tr><td>' + row.info + '<td><tr>'; << html is growing
        console.log('Log: ' + row.info); << working
      });
    });
    console.log(html); // html gets empty here!
    return html; 
  }
}

因此没有返回任何值:

var sysLog = require('logger');

sysLog.init();
sysLog.write('test string1');
sysLog.write('test string2');
console.log(sysLog.readHtml());

要解决它必须非常简单...... 节点是6.7

1 个答案:

答案 0 :(得分:1)

当您使用JavaScript开始时,您的问题与一个非常常见的问题直接相关:

How do I return the response from an asynchronous call?

其中显示了接收异步操作结果的最简单方法,例如.text()正在使用回调。

db.each

要解决这个问题,你需要一个将使用这样的回调调用的函数:

function readHtml()
  var html = ''
  db.serialize(function() {
    db.each(..., function(err, row) {
      // this line executes sometime later
      // after we already returned from readHtml()
    });
  });
  // this line executes right after the call to db.serialize
  // but before db.each calls the callback we give to it.
  // At this point, html is '' because we still didn't read any rows 
  // (they are read asynchronously, sometime later)
  return html;
}

readHtml(); // <-- this is always '' because rows are read at a later point

您的情况还有一个额外的复杂因素,readHtml(function(html) { // <-- this callback gets called once all rows are read console.log(html); }); 每行调用一次回调。通过查看docs,您可以看到db.each在读取所有行时接受额外的db.each回调。您可以使用此回调来表示已完成阅读并传递complete结果。

以下是如何定义html

readHtml