2016-10-15 14 views
1

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

JavaScriptで起動するときの問題は非常に一般的な問題に直接関係する:

How do I return the response from an asynchronous call?

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

あなたの状況はまたdb.eachは行ごとに一回のコールバックを呼び出すことを追加合併症を持っています。 docsを見ると、すべての行が読み取られたときにcompleteコールバックを受け入れることがdb.eachでわかります。このコールバックを使用して、読み取りが完了したことを通知し、htmlの結果を渡すことができます。

は、ここでは、readHtmlを定義することができます方法は次のとおりです。

function readHtml(callback) { // pass in a callback to call once all rows are read and all html is accumulated 
    var html = ''; 
    db.serialize(function() { 
    // read all the rows and accumulate html as before 
    db.each("SELECT rowid AS id, info FROM logger", function(err, row) { 
     html = html + '<tr><td>' + row.info + '<td><tr>'; 
    }, function() { 
     callback(html); // use the second callback to signal you are done and pass the html back 
    }); 
    }); 
} 
+0

あなたの詳細な説明と私の基本的なノード知識を気の毒いただきありがとうございます。それは将来のための良い教訓になります:) –

+0

問題のない仲間、喜んで助ける:) – nem035

関連する問題