0

I have a function that clears two arrays and then populates them with values received from a mysql server.

function sqlget() {
  var arrayA = [];
  var arrayB = [];
  con.query("SELECT * FROM table", function(err,result,fields) {
    if (err) throw err;
    Object.keys(result).forEach(function(key) {
      arrayA.push(result[key].columnA);
      arrayB.push(result[key].columnB);
    });
  });
}

What I would like to be able to do is then call arrayA/arrayB outside of function and have it return the sql information fetched inside the function with something such as...

sqlget()
console.log(arrayA)

Any advice for how this could be done would be much appreciated.

2 Answers 2

1

There are a few things you can do here. You can declare these arrays outside of the function, so you would have something like this:

let arrayA = ['something'];
let arrayB = [];

function sqlget() {
  arrayA = [];
  arrayB = [];

  con.query("SELECT * FROM table", function(err,result,fields) {
    if (err) throw err;
    Object.keys(result).forEach(function(key) {
      arrayA.push(result[key].columnA);
      arrayB.push(result[key].columnB);
    });
  });
}

sqlget();
console.log(arrayA)

Or you could play around, still return the arrays inside the function and return an object with them:

function sqlget() {
  const arrayA = [];
  const arrayB = [];
  
  con.query("SELECT * FROM table", function(err,result,fields) {
    if (err) throw err;
    Object.keys(result).forEach(function(key) {
      arrayA.push(result[key].columnA);
      arrayB.push(result[key].columnB);
    });
  });

  return {
    a: arrayA,
    b: arrayB
  };
}

const arrays = sqlget();

console.log(arrays.a);
console.log(arrays.b);
Sign up to request clarification or add additional context in comments.

Comments

1

You need to define those two arrays outside of the function. When you define a variable inside of {} block or function you can't access outside of this block its called local scope. Please read javascript scope

var arrayA = [];
var arrayB = [];

function sqlget() {
  
  con.query("SELECT * FROM table", function(err,result,fields) {
    if (err) throw err;
    Object.keys(result).forEach(function(key) {
      arrayA.push(result[key].columnA);
      arrayB.push(result[key].columnB);
    });
  });
} 

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.