2

In the following function, I have attempted to run an statment.all query in sqlite3. however the function ends without ever running the callback function.

I cannot pinpoint the problem even after a thorough debug and few experiments. The strangest thing about this is that I have another similar query working perfectly fine within the code. It's included as well in the question.

here's the problematic code:

function gameSetup (questions_num){
var questions = [];

getQuestions.all(questions_num, function (e, rows) {
    console.log("the callback is working!"); // this line never runs

    if (e) {
        return new Promise( (resolve, reject) => {
            reject(e);
        }); 
    }
    else{ 

        var answers, question;
        for (let row of rows)
        {
            answers = [row.correct_ans, row.ans2, row.ans3, row.ans4];
            answers = shuffle(answers);
            question = {"question":row.question, "ans1":answers[0] , "ans2":answers[1] , "ans3":answers[2] , "ans4":answers[3]};
            questions.push(question);   
            console.log(questions);
        }
    }

    return new Promise( (resolve, reject) => {
        resolve(questions);
    });
});}

this is the sql statement:var getQuestions = db.prepare("select * from t_questions order by random() limit ?");

and I have another similar code that works :

app.get("/rooms", checkAuth, (req, res) => {
     getRooms.all((e, data) => {
        if(e) {
            return res.status(500).json(e);
        }
        else if (data.length == 0) {
            res.render('rooms', {items: data, error: "no rooms found"});
        }
        else
        {
            res.render('rooms', {items: data, error: "false"});         
        }
    });
});

with the following statement:

var getRooms = db.prepare("select * from t_games where start_time is null");

I might have given too much info, or too little. feedback on the question would be appreciated since this is my first question on the site.

Shimon k
  • 21
  • 3

1 Answers1

0

I think calling random() in the statement might be where the problem is.

What happens if you try something like:

var getQuestions = db.prepare("select * from t_questions order by ? limit ?")

and

getQuestions.all([random(), questions_num], function (e, rows) { ...

Also, is random() a function you defined somewhere that returns the column to be ordered by? Or maybe Math.random()?

tmwoods
  • 2,353
  • 7
  • 28
  • 55
Heike
  • 11
  • 1
  • 4