如何在其他try块中访问try块中的变量?

Phi*_* YS 3 javascript asynchronous try-catch node.js async-await

http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/在这个链接中,有一些代码可以访问try catch中的变量但是我在我的服务器中尝试这个它不起作用,因为它超出了范围.我怎样才能做到这一点?

try {
  const foo = "bar"
} catch (e) {
  console.log(e)
}

try {
  console.log(foo) -> is not defined
} catch (e) {
  console.log(e)
}
Run Code Online (Sandbox Code Playgroud)

Ion*_*zău 12

该帖子的作者显然在那里犯了一个错误 - 它发生在我们所有人身上.

因此,const声明是块范围的,就像文档说:

常量是块范围的,非常类似于使用let语句定义的变量.常量的值不能通过重新赋值来改变,也不能重新声明.

这就是为什么你不能在try-catch块之外访问它.

解决问题:

  • 要么使用var而不是const:

    try {
      // When declared via `var`, the variable will
      // be declared outside of the block
      var foo = "bar"
    } catch (e) {
      console.log(e)
    }
    
    try {
      console.log(foo)
    } catch (e) {
      console.log(e)
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者,你可以声明的变量外try-catch,使用let:

    // Maybe it's clearer to declare it with let and 
    // assign the value in the first try-catch
    let foo;
    try {
      foo = "bar"
    } catch (e) {
       console.log(e)
    }
    
    try {
      console.log(foo)
    } catch (e) {
      console.log(e)
    }
    
    Run Code Online (Sandbox Code Playgroud)