I'm a newbie in Javascript and I was trying to make a function to return an array of itens that I got from my DB. First I tried this:
function getItens(userId){
    var arr = new Array;
    var result;
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'XXXXXX',
      password : 'XXXXXX',
      database : 'XXXXXX',
    });
    connection.connect();
    connection.query('SELECT * from itens where userId = '+ userId function(err, rows, fields){
         if (err) throw err;
         arr = rows.slice()
    });
    return arr;
    connection.end();
}
Then I realized there was a scope problem there, and after some research I tried to emulate a static variable like this:
function getItens(userId){
  (function (){
      var resultado;
      Result = function(valor) { resultado = valor; }; 
      Result.prototype.getResultado = function (){return resultado};
      Result.prototype.setResultado = function (valor){ resultado = valor; };
  })();
  var ar = new Result([]);
  var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'XXXXXX',
      password : 'XXXXXX',
      database : 'XXXXXX',
    });
  connection.connect();
  connection.query('SELECT * from itens where userId = '+ userId , function(err, rows, fields){
        if (err) throw err;
        ar.setResultado(rows.slice());
  });
  return ar.getResultado();
  connection.end();
}
But it didn't work, what am I doing wrong?
 
     
    