问题
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.
回答1:
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);
}
来源:https://stackoverflow.com/questions/36656716/change-a-variable-from-outside-its-scope