Building strings from sqlite3 databse in nodejs

I'd like to write a JS script what works with nodejs and operates on sqlite3 database. The plan is to get data from the database and surrounding with "script" tags. My snippet is the following:

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

The database only contains a "test" function implementation. The expected result is:

<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>

In spite of this i got

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

I don't understand why is the order of the strings changed. Why isn't the function string inside the "script" tags?

db.get is an asynch operation, so closeCode will run before the DB operation has finished.

You should move closeCode and printMe into the async operation so they run after the db update works:

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