Search code examples
javascriptnode.jsnode-mysql

Javascript scope. How to retrieve information from a callback function? Node-mysql


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?


Solution

  • You give a callback to the query function because it isn't immediately executed.

    At the line just after the call to connection.query, the callback hasn't yet run.

    You must use the data in the callback you provide. Note that a common pattern is to provide a callback to your querying function :

    function fetchItens(userId, callback){
    
        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()
             callback(arr);
        });
        connection.end();
    }
    
    fetchItens(someId, function(arr){
       // use arr
    });