0

I'm running into a small problem while trying to get data out of a sqlite database to a string. Here is the code:

router.get('/', function(req, res) {
    var db = req.db;
    var thisShouldWork = 'Hmmm';

    db.all('select rowid as id, value from test', function(err, rows) {
        rows.forEach(function(row){
            console.log(row.id + ": " + row.value);
            thisShouldWork += 'Heeee';
        });
    });
    thisShouldWork += 'What?';
    console.log(thisShouldWork.toString());

    res.send(thisShouldWork);
});

The variable 'thisShouldWork' just outputs 'HmmmWhat?' at the end of this code, while it should have a few 'Heeee's in there as well. Also, console.log prints 3 lines of data so the for loop is definitely executing. Am I doing something wrong without realizing or is there a different/better way to achieve the same thing?

1 Answer 1

1

The callback is executed asynchronously.

Whatever you want to do afterwards must be moved at the end of the callback:

router.get('/', function(req, res) {
    var db = req.db;
    var thisShouldWork = 'Hmmm';

    db.all('select rowid as id, value from test', function(err, rows) {
        rows.forEach(function(row){
            console.log(row.id + ": " + row.value);
            thisShouldWork += 'Heeee';
        });
        thisShouldWork += 'What?';
        console.log(thisShouldWork.toString());

        res.send(thisShouldWork);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for the answer! I just tried it and its working perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.