如何在try catch块中使用const

per*_*mon 10 javascript syntax node.js ecmascript-6

const是块级变量,所以当我尝试怀疑代码时

try{
   const foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}
Run Code Online (Sandbox Code Playgroud)

const隐藏在 {}

但

const foo ;
try{
    foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}
Run Code Online (Sandbox Code Playgroud)

不工作,因为const必须是声明初始化.
所以我应该怎么尤斯const在try..catch块?

Aro*_*ron 18

你已经击中了头部,因为块的范围你不能const在try catch块中声明一个并在块外面使用它.

你有2 3个选择:

用途let:

let foo;
try{
    foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}
Run Code Online (Sandbox Code Playgroud)

或者如果在try catch块之后只有很少的代码,并且这一切都取决于它的成功try,你可以将其余的代码放在try:

try{
    const foo = bar[global.name].foofoo[global.name2];
    return foo;
}catch (err){
    console.log(error(err.message));
}
Run Code Online (Sandbox Code Playgroud)

编辑

选项3的灵感来自@Yury Tarabanko的评论:如果可能的话,将try catch部分模块化为它自己的函数,其输出应该是new的值const:

function trycatch() {
    try {
        return bar[global.name].foofoo[global.name2];
    } catch (err) {
        console.log(error(err.message));
        return undefined; // or whatever you want
    }
}

const foo = trycatch(); // === bar[global.name]... if succeeded, otherwise === the return value from the catch block
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢选项 3,但如果您必须停止 catch 中的初始函数,则不能使用它。 (2认同)