NodeJS context issues


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

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


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

Solution courtesy of: user2038643


There is currently no discussion for this recipe.

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