0
function get_all_channels_by_order(){
    var foobar = false

    mysql_connection.connect()
    mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", function(){
        foobar = true
    })
    mysql_connection.end()
    console.log(foobar)
}

I need foobar to return true but instead it returns false. This is due of course to the JavaScript scopes, but I was wondering is there any way to overcome this? Or is it impossible?

I am sorry to ask such a common question, but I have looked at several other Stack Overflow questions and they have not helped, I also tried lots of other code rather than this but no successes.

0

1 Answer 1

0

EDIT: While my answer holds true, apparently the OP's real issue was that he was trying to access a variable that was being modified by a callback, before the callback returned.

Try the code below. I created a variable called 'that', which stores a reference to the scope you're in. Then, everytime I want the correct foobar, I just prefix it with "that."

var mysql_connection = {};
mysql_connection.connect = function(){
   console.log("call to mysql_connection.connect");
}

mysql_connection.query = function(query,cb){
   console.log("call to mysql_connection.query with query of",query);
   if(cb){
      cb();
   }
}
mysql_connection.end = function(){
   console.log("call to mysql_connection.end");
}

function get_all_channels_by_order(){
    var that = this;
    that.foobar = false;
    console.log("foobar=",that.foobar);

    mysql_connection.connect()
    mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", function(){
        that.foobar = true
    })
    mysql_connection.end()
    console.log("foobar=",that.foobar);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just tried this, still returns false.
And? Your code still prints foobar=false. And you're closing connection before query is finished.
Chill. I assumed sync. Read edits before writing. As posted my code logs true. Notice I defined the mysql methods

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.