javascript - 等价于 try...catch 作为表达式
问题描述
我正在寻找一种方法来做类似的事情:
myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;
我知道这是不正确的,但你明白了。我只是想知道是否有一种优雅的方式来做到这一点?
解决方案
你目前能做的最好的可能是 IIFE:
myVar = (() => {
try {
return someFunction();
} catch (e) {
}
})() ?? defaultValue;
推荐阅读
- c# - 继承时无法访问类字段
- elasticsearch - Elasticsearch,搜索以开头的单词
- php - 如何通过 cURL 正确地将 POST 请求发送到 REST API?
- scala - 从 trait 意外行为的案例类继承
- reactjs - 将图像的 URL 从 firebase 存储存储到 firebase 数据库 - URL 在网络空间中丢失
- r - igraph:edges_from 与 edge_to。有什么区别?
- flutter - 如何从flutter中的isolate调用平台代码?
- ruby-on-rails - 如何从另一个模型字段更新模型字段
- python - 为什么我在 matplotlib 的 x 轴上得到垃圾日期值?
- mongodb - 如何将时间戳添加到猫鼬模式子字段?