Search code examples
node.jsbotframework

Boolean not set to true node.js


I have this code: at the beginning of the file I initialized the variable (var loginState = false;) Why console.log give me false, although I change it to true

try {
        const client = new SimpleGraphClient(tokenResponse.token);
        const me = await client.getMe();

            sql.connect(config, async function (err){
                if (err) console.log(err);
                var request = new sql.Request();
                request.query(`SELECT * FROM tradebot.accounts WHERE username='${username}' AND password='${password}'`, async function (err, recordset){
                    if (err) console.log(err);
                    console.log(recordset);
                    if (recordset.recordset.length == 1) {
                        loginState = true;
                    } else {
                        loginState = false;
                    }
                    sql.close();
                });
            });
            console.log(loginState);
            if (loginState == true) {
                await turnContext.sendActivity({
                    text: 'Work',
                    attachments: [CardFactory.adaptiveCard(mainmenu)]
                });
            } else {
                await turnContext.sendActivity({
                    text: 'Dont work',
                    attachments: [CardFactory.adaptiveCard(internal_login)]
                });
            }            
    } catch (error) {
        throw error;
    }

Solution

  • The reason is because you are setting the value to variable inside a callback function : You have to await your query result. The way you are calling the query is not feasible.


    Take a look at - https://www.npmjs.com/package/mysql2

    Also change this part -

    sql.connect(config, async function (err){
       if (err) console.log(err);
        var request = new sql.Request();
        request.query(`SELECT * FROM tradebot.accounts WHERE username='${username}' AND password='${password}'`, async function (err, recordset){
         if (err) console.log(err);
         console.log(recordset);
          if (recordset.recordset.length == 1) {
            loginState = true;
          } else {
            loginState = false;
          }
         sql.close();
        });
     });
    

    Change this to something like this :

     try{
         let connection = await sql.connect(config);
         let query1 = await connection.query(`SELECT * FROM tradebot.accounts WHERE username='${username}' AND password='${password}'`);
    
          if (query1[0].recordset.length == 1) {
               loginState = true;
           } else {
               loginState = false;
           }
     }catch (err){
        // do something here
     }