【问题标题】:how can I access to a variable in try block in other try block?如何在其他 try 块中访问 try 块中的变量?
【发布时间】:2017-11-02 05:25:24
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js asynchronous async-await try-catch


    【解决方案1】:

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

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

    常量是块范围的,很像使用 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)
      }
      
    • 或者你可以在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)
      }
      

    【讨论】:

    • 正如你在帖子中看到的,作者使用const,它是如何工作的?
    • @PhillipYS 我会说这是一个错误。
    • @PhillipYS 我刚试过,是的,这是作者的错误。不错的收获!
    • 是的,我想知道在 Node 8.0.0 发布后范围系统是否发生了变化。我讨厌尝试/捕捉这么多h
    • @PhillipYS 不,这不是与 Node 相关的更改,而是在 specs 中。
    猜你喜欢
    • 2016-02-17
    • 2018-08-27
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多