Javascript - 调用If / Else Block之外的变量返回Undefined [英] Javascript - Calling A Variable From Outside Of If/Else Block Returns Undefined

查看:88
本文介绍了Javascript - 调用If / Else Block之外的变量返回Undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为这是你如何在if / else $ block global(Case 3)。

  connection.query(sql,function(err,rows){

//处理错误
如果(错误){
//记录错误和死亡
}

//如果成功 - 立即记录结果(更改为导出结果)
else {
//console.log (rows);
foo = rows;

}

});

console.log(foo); // Out:undefined

为什么我不能在函数之外访问变量?



解决方案

好的,这里的问题是理解什么是异步性是。与@AmmarCSE聊天后,看着这个伟大的问题在这里我明白我的结构我的问题(和我的代码,显然)不正确。



我试图访问一个未定义的变量直到函数完成运行(对远程数据库的SQL查询显然需要更长时间才能完成,然后运行本地脚本)。但是,如果我以异步方式构造我的代码,则只有在函数完成时调用变量



事实证明 - 并不是变量范围的问题,而是变量定义时间的问题(不确定这是否是脚本中正确的术语,变量得到了定义 - CS专业,随意编辑正确的术语)。

无论如何,这里是新的代码:

  runSQL(函数(结果){

//做任何你想要的结果 - 它们被定义!!
console .log(result);
)};

函数runSQL(回调){

connection.query(sql,function(err,rows){

//处理错误
如果(错误){
//记录错误和死亡
}

//如果成功 - 立即记录结果(更改为导出结果)
else {
callback(rows);
}

});



解决方案

错误回调中,它有自己的作用域定义。因此, foo 仅对该闭包和任何嵌套闭包可见。对于案例3,您在链接中提到了

  var a = 1; 

函数four(){
if(true){
var a = 4;
}

警报(a); // alert'4',不是全局值'1'
}

即使该变量是在 if 块中定义的,也会在正确的闭包中 function four()它的父功能是可见的。



但是,您正在制作 foo 全球通过不加前缀 var 。然而,回调后的日志记录导致未定义,因为此时 foo 尚未定义。如果你在错误回调中登录,它会起作用,但我建议你重新调整你的代码以使用回调的异步性质。

  connection.query(sql,function(err,rows){

//处理错误
if(err){
//记录错误和放大; Die
}

//如果成功 - 现在记录结果(更改为导出结果)
else {
//console.log (rows);
foo = rows;

}
console.log(foo);
});


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, foo is only visible to that closure and any nested closures. For case 3 you have mentioned in the link

var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

they alert the variable within the correct closure, function four(), even if that variable was defined in the if block, it is visible to its parent function.

However, you are making foo global by not prefixing with var. Yet, logging after the callback results in undefined because at that point, foo was 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

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);
    });

这篇关于Javascript - 调用If / Else Block之外的变量返回Undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆