相当于try ... catch作为表达式 [英] Equivalent of try...catch as an expression

查看:84
本文介绍了相当于try ... catch作为表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种类似的方法:

Im looking for a way to do something like:

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

我知道这是不正确的,但是您明白了.我只是想知道是否有一种优雅的方法?

Which I know isn't correct but you get the idea. I just wondered if there was an elegant way to do this?

推荐答案

目前最好的方法可能是IIFE:

The best you can do currently is probably an IIFE:

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

这篇关于相当于try ... catch作为表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆