0

I'm trying to understand what is going on here. I am trying to change a variable defined outside of a function scope. I come from a Java background and this set of code has taken me by surprise

var dayIsEmpty = false;

selectByDate.on('end', function(result) {

    if(result.rowCount == 0) {
        console.log('isEmpty');
        dayIsEmpty = true;
    } else {
        console.log('isNotEmpty');
        dayIsEmpty = false;
    }
    console.log('isEmpty?' + dayIsEmpty);
    console.log('Finished Select from UsageByDay');
});
console.log('outside of block isEmpty?' + dayIsEmpty);

I noticed that

outside of block isEmpty? false

is called before any of console output defined within the function is called. First of all... what is going on? And secondly, how would you work around this.

shinjw
  • 3,329
  • 3
  • 21
  • 42
  • 1
    Why do you think the function is ever being called? – Chris Farmer Jul 06 '15 at 22:09
  • 3
    Nothing to do with function scope. Everything to do with call sequence. – T.J. Crowder Jul 06 '15 at 22:09
  • 1
    what's going on? asynchronous function. how to work around this? you don't, you learn to use it – Jaromanda X Jul 06 '15 at 22:10
  • The event `end` must fire first for your function to be triggered by the event handler. That is why you see the log statement first. HTML5 Rocks has a solid article on async programming: http://www.html5rocks.com/en/tutorials/async/deferred/ – laughingpine Jul 06 '15 at 22:14

0 Answers0