copy values from sqlite3 db to a global array in node.js

i have use the node_sqlite3 module and i have try the following example:

var sqlite = require('sqlite3').verbose();
var db = new sqlite.Database("/var/www/signals/db/app3.db");

var matrixSignals = new Array();
var i;

i = 0;
db.all('SELECT * FROM tbl_signals', function(err,rows){
    rows.forEach(function(row) {
        matrixSignals[i] = new Object();
        matrixSignals[i].signalID = row.signalID;
        matrixSignals[i].connID = row.connID;
    console.log('1:' + matrixSignals.length);
console.log('2:' + matrixSignals.length);

in the console output 1 the length is correct but in the console output 2 the length is always 0. How i will set the matrixSignals as a global variable?

Problem courtesy of: kyrkat


The reason this doesn’t work has to do with how Node.js
operates in general. In node, all code is executed asynchronously; at the time you are logging output 2, matrixSignals still has a length of 0. This is because after you fire off the database query, the code continues to execute. Logging output 1 is only executed after
the database query has finished, which is why it returns the correct results.

For this reason, the simple answer to your question is that there is no way to set matrixSignals to be a global variable. If all of your logic is truly dependent on the values in that array, then your logic should be in the callback to the database call – so that it only executes that code once the data has been retrieved from the database. If you just want the syntax to be cleaner, you could potentially use something like node-promise ( but I think that’s probably more effort than its worth.

Solution courtesy of: BlueMoon

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » copy values from sqlite3 db to a global array in node.js

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录