Syntax 咖啡脚本try/catch的简短符号

Syntax 咖啡脚本try/catch的简短符号,syntax,coffeescript,try-catch,shortcut,Syntax,Coffeescript,Try Catch,Shortcut,我有时会编写如下代码: try doSomething() catch e handleError e 这不是好的干净的coffeescript代码应该是什么样子 有没有办法写: try doSomething() catch e handleError e #<-- will not compile 试试doSomething() catch e handleError e#编写try/catch one-liner的工作原理与使用then关键字的if then one-li

我有时会编写如下代码:

try doSomething()
catch e
  handleError e
这不是好的干净的coffeescript代码应该是什么样子

有没有办法写:

try doSomething()
catch e handleError e   #<-- will not compile
试试doSomething()

catch e handleError e#编写try/catch one-liner的工作原理与使用
then
关键字的if then one-liner或loop one-liner类似:

try doSomething()
catch e then handleError e
finally cleanUp()
如果您愿意,您甚至可以在一行中使用:

try doSomething() catch e then handleError e finally cleanUp()
交叉过帐来源:

我发现你会写作

try
   compute something
catch error
    handle error 
unless error?
    handle success
这是可能的,因为CS将
catch
子句的变量放入周围的范围,而JS没有这样做。有人甚至可能会争辩说,在这个位置上说
除非出错?
else
(这不是
if
子句)和
continue
(这不是循环)更清楚

坚持使用OneLiner的人甚至可以写作

try compute something catch error then handle error unless error? then handle success
这有点酷,也有点不可读


最后一个
子句必须放在
之前,当然,除非

另外,
然后
是可选的,没有
。因此,这也是有效的:
尝试doSomething()catch e然后handleError e finally cleanUp()
catch e
handle e
在一行中时,您仍然需要
然后
否则它无法编译:对不起,我不清楚,我的意思是,
然后
-子句是可选的。谢谢你的评论。啊,我明白了。异步处理错误时,捕获错误而不使用then子句也非常有用。在这种情况下,您通常不希望在try或catch块中回调,但在之后:
try result=a()catch e;如果e?然后cb e else cb null,result
这是可能的,因为coffee脚本(而不是vanilla JS)会自动从catch范围中提取错误变量。