0

I have the code snippet bellow which actually is a function that makes a query on a SQL database(used tedious for that). All I want is to get the data from DB and use them on a web-page. The issue is that: inside the request.on()... I'm calling date.setMyData() function. Still inside the request.on('row', function(columns)....if calling console.log(date.getMyData()) it successfully returns my data.

BUT, if trying to call date.getMyData outside the request.on('row', function(columns) ...I get NULL... Is there anything that I'm missing here?

  var date = new DBData();

    function executeStatement() {
  request = new Request(queryString, function(err, rowCount) {
    if (err) {
      console.log(err);
    } else {
     console.log(rowCount + ' rows');
    }
    connection.close();
  });

  request.on('row', function(columns) {

   columns.forEach(function(column) {
      if (column.value === null) {
        console.log('NULL');
      } else {
          date.setMyData(columns);


          //WHY THIS CODE RETURNS MY DATA?
          console.log(date.getMyData()); 

      }
    });
  });

  request.on('done', function(rowCount, more) {
    console.log(rowCount + ' rows returned');
  });

  connection.execSql(request);
}

function DBData(){
    var myData = null;

    this.setMyData = function(obiect){
        myData = obiect;
    };

    this.getMyData = function(){
        return myData;
    };
};

 console.log(date.getMyData()); //WHY I GET 'NULL' HERE?
noTest
  • 159
  • 1
  • 3
  • 12
  • If `Request` is asynchronous, it will complete in its own time, invoking `setMyData()` well after `console.log()`. Related: [Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski Feb 07 '15 at 22:03

1 Answers1

0

When you run that code, the order of execution will be

var date = new DBData()
console.log(date.getMyData()) //  null at this point

// end of execution

The function executeStatement() gets defined, but it is not executed right away. It will be presumably executed at a later time when you call it, at which point it will populate your 'var date', hence it will display the correct data correctly when you console.log(date.getMydata()) inside the callback of executeStatement().

Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33