javascriptmysqlnode.jsfacebook-messenger-bot

Node Mysql query with incremental variable


I have problem why my variable in query dont increment? My code:

function processMessage(event) {
    if (!event.message.is_echo) {
        let message = event.message;
        let senderId = event.sender.id;

    console.log("Received message from senderId: " + senderId);
    console.log("Message is: " + message);
    console.log();
    var user = {
        user_name: '',
        question_index: 0,
    }


    if (message.quick_reply.payload === 'Pass') {
        connection.query("SELECT text FROM quiz_questions WHERE quiz_id = ?", [question_index], function(error, results, fields) {
            if (error) throw error;
            let jsonQuestionResult = getRealResults(results);
            connection.query("SELECT text FROM question_option WHERE quiz_question_id = ?", [question_index], function(error, results, fields) {
                if (error) throw error;
                let jsonAnswerResult = getRealResults(results);
                console.log(jsonAnswerResult[0]);
                sendQuestionAnswer(senderId, jsonQuestionResult[0].text, jsonAnswerResult[0].text, jsonAnswerResult[1].text, jsonAnswerResult[2].text);
                user.question_index++;
            })
        })
    }
}
}

I increment user.question_index but it doesnt apply when i call processMessage function what is wrong there? Or how to make that when i call quick reply with payload(pass) it will show next column from database?


Solution

  • Define your user variable outside the processMessage. Everytime you call the method it gets reinitialised to default 0. So If you want to persist the value

    var user = {
            user_name: '',
            question_index: 0,
        }
    
    
    function processMessage(event) {
        if (!event.message.is_echo) {
            let message = event.message;
            let senderId = event.sender.id;
    
        console.log("Received message from senderId: " + senderId);
        console.log("Message is: " + message);
        console.log();
    
    
    
        if (message.quick_reply.payload === 'Pass') {
            connection.query("SELECT text FROM quiz_questions WHERE quiz_id = ?", [question_index], function(error, results, fields) {
                if (error) throw error;
                let jsonQuestionResult = getRealResults(results);
                connection.query("SELECT text FROM question_option WHERE quiz_question_id = ?", [question_index], function(error, results, fields) {
                    if (error) throw error;
                    let jsonAnswerResult = getRealResults(results);
                    console.log(jsonAnswerResult[0]);
                    sendQuestionAnswer(senderId, jsonQuestionResult[0].text, jsonAnswerResult[0].text, jsonAnswerResult[1].text, jsonAnswerResult[2].text);
                    user.question_index++;
                })
            })
        }
    }
    }