-1

I have written some code where I have a variable that changes if I enter an if statement inside the function of an sql query. However the function does not change globally only locally. The code is the following:

app.post("/energy/api/Admin/users", function(req,res)
        var correct=0
        sql.query(`SELECT apikey,privileges FROM users WHERE apikey=?`,[req.user.apikey],(err,res1) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            else if (res1.length && res1[0].privileges=="superuser"){
                console.log("Apikey correct");
                correct=1;
            }       
            else  correct=0;
        });
        console.log(correct);
        if (correct==1){
                 ....
                }

Note: The if (correct==1) never happens even if correct is set to 1 inside the query function. I think this is not supposed to happen with variables in javascript. Why does this happen?

  • 3
    Seems like `sql.query()` is asynchronous. – Tyler Roper Jan 22 '20 at 15:12
  • @TylerRoper how can I fix this to work? –  Jan 22 '20 at 15:12
  • 3
    The `if (err) ... else if (res1.length ...) else ...` section of your code is in a callback. This is all the code that must wait to execute until *after* the query is complete. Notice your `if (correct == 1)` is **not** in there; it evaluates long before `correct` gets changed. You can evaluate the value of `correct` *inside* of the callback instead. Generally speaking though, you may just want to read up on [asynchronous JavaScript](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), callbacks, etc. – Tyler Roper Jan 22 '20 at 15:14
  • are you using `mssql` package for sql interaction? if yes, you could simply use await and use the value returned. – Ashish Modi Jan 22 '20 at 15:16

2 Answers2

0

Change it it promise style as you are trying to access the value before even it is set. the code will look like this

app.post("/energy/api/Admin/users", async function (req, res) {
  const correct = await getResults(req.user.apikey);
  console.log(correct);
  if (correct == 1) {
  }
});

function getResults(key) {
  return new Promise((resolve, reject) => {
    sql.query("SELECT apikey,privileges FROM users WHERE apikey=?", [key], (err, res1) => {
      if (err) {
        console.log("error: ", err);
        reject(err);
      } else if (res1.length && res1[0].privileges == "superuser") {
        console.log("Apikey correct");
        resolve(1);
      } else {
        resolve(1);
      }
    });
  });
}


Ashish Modi
  • 7,529
  • 2
  • 20
  • 35
0

The query function is indeed asynchronus. The easy way is to work with async await which handles the promise responses. You could try this:

  app.post("/energy/api/Admin/users", async function(req,res)
            var correct=0
           let response = await sql.query(`SELECT apikey,privileges FROM users WHERE apikey=?`,[req.user.apikey]);
// then here you can check for the response if its an error and so on
                if (response) {
                    console.log("response: ", response);
                  //... your code now you can use the response without thiunking of asynchronity
Burak Ayyildiz
  • 325
  • 1
  • 6