我怎样才能访问其他尝试块try块中的variables?

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

try { const foo = "bar" } catch (e) { console.log(e) } try { console.log(foo) -> is not defined } catch (e) { console.log(e) } 

那篇文章的作者显然在那里犯了一个错误,这发生在我们所有人身上。

所以, const声明是块范围的,就像文档所说:

常量是块范围的,就像使用let语句定义的variables一样。 一个常量的值不能通过重新赋值而改变,并且不能被重新声明。

这就是为什么你不能在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) } 
  • 或者你可以在try-catch之外声明variables,使用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) }