0

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.

2 Answers 2

1

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);
   }
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.