I thought this is how you make a variable inside a if/else block global (Case 3).
connection.query(sql, function (err,rows){
//Handle Errors
if(err){
//Log The Error & Die
}
//If Successful - Log Results For Now (Change To Export Results)
else {
//console.log(rows);
foo = rows;
}
});
console.log(foo); // Out: undefined
Why can't I access the variable outside of the function?
SOLUTION
Well, the problem here was one of understanding what asynchronicity really is. After chatting with @AmmarCSE and looking at this great question here on SO I understood that I structured my question (and my code, obviously) incorrectly.
I was trying to access a variable that is not defined until the function finishes to run (an SQL query to a remote DB obviously takes longer to finish then running a local script). If I structure my code asynchronically, however, the variable only gets called once the function finishes.
This, as it turns out - is not a problem of variable scope, really, but of variable defining time (not sure if that's the correct terminology for the time in the script where the variables get defined - CS majors, feel free to edit in the correct term).
Anyway, Here is the new code:
runSQL(function(result){
//Do Whatever you want with the results - they're defined!!
console.log(result);
)};
function runSQL(callback){
connection.query(sql, function (err,rows){
//Handle Errors
if(err){
//Log The Error & Die
}
//If Successful - Log Results For Now (Change To Export Results)
else {
callback(rows);
}
});
}
When you are in the
error callback, it has its own scope defined. Therefore,foois only visible to that closure and any nested closures. For case 3 you have mentioned in the linkthey alert the variable within the correct closure,
function four(), even if that variable was defined in theifblock, it is visible to its parent function.However, you are making
fooglobal by not prefixing withvar. Yet, logging after the callback results inundefinedbecause at that point,foowas not yet defined. If you log within the error callback it will work but I advise you restructure your code to work with the asynchronous nature of callbacks