Home > other >  Change value of variable inside SQL query
Change value of variable inside SQL query

Time:04-05

I hate to ask such a simple question but I can't find an answer anywhere.

I am trying to push the sql results to results2, if I print out the results2 value inside of the connection query it shows the array but when I try to return or print it outside it shows as undefined.

Code:

function getUserData(cookie){
  const sqlquery = "SELECT * FROM `users` WHERE `cookie` = ?"
  const params = [cookie];

  let results2 = [];
  connection.query(sqlquery, params, function(error, results, fields){
    if(error) throw error;
    if(results && results.length){
      results2.push(results[0]);
    }else{
      return("invalid");
    }
  })
  console.log(results2)
  return(results2);
}

I have searched and read through documentations but I can't find where I am messing up.

CodePudding user response:

Your issue is that JavaScript is synchronous (tries to do as much as it can at once) unless you tell it not to be. It is returning reults2 before it has actually populated it because it is faster for it to do it that way. So you need to make the function as a whole asynchronous by adding async before function and adding await before connection.query AND before wherever you are calling getUserData (as in await getUserData(var1, var2)).

An explanation of async functions and await is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

You may start getting errors about functions not begin asynchronous, as async functions need to nest to work (anything that awaits needs to be in an async function itself).

CodePudding user response:

Welcome to the world of callbacks and async ops.

I am trying to push the sql results to results2, if I print out the results2 value inside of the connection query it shows the array but when I try to return or print it outside it shows as undefined.

Here console.log(results2) runs first and in the callback, you are assigning values to results2. So, you are unable to see it.

You can use await with the query:

//const util = require('util');

function getUserData(cookie){
  const sqlquery = "SELECT * FROM `users` WHERE `cookie` = ?"
  const params = [cookie];

  let results2 = [];
  try {
  // if not able to use await promisfy it using 
  // const query  = util.promisify(conn.query).bind(connection);
  // const result = await query(sqlquery, params);
  const result = await connection.query(sqlquery, params);
  results2.push(result);
 } catch(e) {
   console.log(e);
   }
  • Related