我试图在node.js脚本中使用sqlite3,我正在使用这个库:
https://github.com/mapbox/node-sqlite3
但我希望数据库中的调用是同步的而不是异步的,这是我使用的代码示例:
var tests = [];
db.serialize(function() {
db.each("SELECT lot_id, status FROM TestTable ORDER BY lot_id ASC", function(err, row) {
tests.push(row.status);
console.log("Read "+row.lot_id+" state: "+row.status);
});
});
db.close();
for (i = 0; i < tests.length; i++) {
//Do something
}
当执行到达for循环时,由于tests数组仍然为空而继续执行,我如何按顺序执行此指令?
感谢
答案 0 :(得分:4)
在完整回调中执行for循环
var tests = [];
db.serialize(function() {
db.each("SELECT lot_id, status FROM TestTable ORDER BY lot_id ASC", function(err, row) {
tests.push(row.status);
console.log("Read "+row.lot_id+" state: "+row.status);
}, function() { // this callback is executed when the query completed
for (i = 0; i < tests.length; i++) {
// Do something
}
});
});
db.close();