我想编写一个与nodejs一起使用的JS脚本,并在sqlite3数据库上运行。计划是从数据库和周围的“脚本”标签获取数据。我的片段如下:
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('/var/www/db/js.sqlite');
var MyRandomCode =
{
code: "<script>"
}
function appendToCode(snippet) {
MyRandomCode.code += snippet;
}
function printMe() {
console.log(MyRandomCode.code);
}
function closeCode() {
MyRandomCode.code += "</script>";
}
printMe();
randomNode("defun", MyRandomCode);
printMe();
closeCode();
function randomNode(name, MyRandomCode) {
db.get("SELECT tag_value FROM tags WHERE tag_name=\"" + name + "\"", function(err, rows) {
if (err) throw err;
appendToCode(rows['tag_value']);
});
}
数据库仅包含“测试”功能实现。 预期结果是:
<script>
function test() {
a = 5;
c += a + b;
"foo";
var foo = 5;
const bar = 6, baz = 7;
switch ("foo") {
case "foo":
return 1;
case "bar":
return 2;
}
for (var i = 0; i < 5; ++i) {
console.log("Hello " + i);
}
for (var i in [ 1, 2, 3 ]) {
console.log(i);
}
for (var i = 0; i < 5; ++i) console.log("foo");
}
</script>
尽管如此,我还是
<script></script>function test() {
a = 5;
c += a + b;
"foo";
var foo = 5;
const bar = 6, baz = 7;
switch ("foo") {
case "foo":
return 1;
case "bar":
return 2;
}
for (var i = 0; i < 5; ++i) {
console.log("Hello " + i);
}
for (var i in [ 1, 2, 3 ]) {
console.log(i);
}
for (var i = 0; i < 5; ++i) console.log("foo");
}
我不明白为什么字符串的顺序发生了变化。为什么函数字符串不在“script”标记内?
答案 0 :(得分:1)
db.get
是一个异步操作,所以closeCode
将在数据库操作完成之前运行。
您应该将closeCode
和printMe
移到异步操作中,以便它们在数据库更新工作后运行:
function randomNode(name, MyRandomCode) {
db.get("SELECT tag_value FROM tags WHERE tag_name=\"" + name + "\"", function(err, rows) {
if (err) throw err;
appendToCode(rows['tag_value']);
closeCode();
printMe();
});
}