首页 > 解决方案 > 等价于 try...catch 作为表达式

问题描述

我正在寻找一种方法来做类似的事情:

myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

我知道这是不正确的,但你明白了。我只是想知道是否有一种优雅的方式来做到这一点?

标签: javascriptfunctiontry-catchexpressionmetaprogramming

解决方案


你目前能做的最好的可能是 IIFE:

myVar = (() => {
  try {
    return someFunction();
  } catch (e) {
  }
})() ?? defaultValue;

推荐阅读