NodeJS context issues

Problem

I'm having issues with writing to a socket (with http) from a sqlite (sqlite3) libary in Node.JS

https://gist.github.com/RyanCopley/6004c3ce372e060bbf18

Lines 68 to 75, I have 4 attempts to write. Outside of the db.each, everything works in any context. INSIDE of it, it crashes miserably. I'm not entirely sure why, but I feel like there is a conflict between the two libraries

BTW I already know concatenating the SQL statement is bad :3

Problem courtesy of: Ryan Copley

Solution

This is because the callback function in db.each is called asynchronously. This means that line 79: res.end() will be called before res.write("Found row!");, triggering an error.

I think what you want to do is something like this:

db.serialize(function() {
    that.res.write("["); // works
    db.each("SELECT * FROM messages WHERE channel = '"+q.chan+"' AND id > "+q.since+" ORDER BY id", function(err, row) {
        res.write("Found row!"); //does not work
        that.res.write("Found row!"); //does not work
        console.log("Found row!");
    });

    res.write("]");//works
});
Solution courtesy of: user2038643

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.