我在尝试将数据从 sqlite 数据库获取到字符串时遇到了一个小问题。这是代码:
router.get('/', function(req, res) {
var db = req.db;
var thisShouldWork = 'Hmmm';
db.all('select rowid as id, value from test', function(err, rows) {
rows.forEach(function(row){
console.log(row.id + ": " + row.value);
thisShouldWork += 'Heeee';
});
});
thisShouldWork += 'What?';
console.log(thisShouldWork.toString());
res.send(thisShouldWork);
});
变量“thisShouldWork”仅输出“HmmmWhat?”在此代码的末尾,同时它也应该有一些“Heeee”。另外,console.log 打印了 3 行数据,因此 for 循环肯定正在执行。 我是否在没有意识到的情况下做错了什么,或者是否有不同/更好的方法来实现同样的目标?
最佳答案
回调是异步执行的。
无论您之后想要做什么,都必须在回调结束时移动:
router.get('/', function(req, res) {
var db = req.db;
var thisShouldWork = 'Hmmm';
db.all('select rowid as id, value from test', function(err, rows) {
rows.forEach(function(row){
console.log(row.id + ": " + row.value);
thisShouldWork += 'Heeee';
});
thisShouldWork += 'What?';
console.log(thisShouldWork.toString());
res.send(thisShouldWork);
});
});
关于javascript - 尝试使用 Node 获取sqlite数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093064/