返回并扔在一行上,不带分号

Return and throw on one line without semi-colon

本文关键字:一行 返回      更新时间:2023-09-26

有没有办法返回一个胖箭头 anon 函数,运行条件,如果它为 false,则返回错误,如果它是真的,则返回 true,所有这些都在一行上,没有分号?

let example = (d) => { if (get(d, 'facebook_user.id')) return true; throw new Error('Missing `facebook_id` from request') }

正在尝试找到一种更好的方法来写上面没有分号,限制是我必须返回并扔掉。想法?思潮?

下面

怎么样?

let example = (d) => { get(d, 'facebook_user.id') || (() => {throw new Error('Missing `facebook_id` from request')})() };

可以创建一个函数来包装条件和错误消息并抛出/返回。

export function ifThrow (condition, errorMessage) {
  if (condition) throw new Error(errorMessage)
  return true
}
let check_facebook_id = (d) => ifThrow(!get(d, 'facebook_id'), 'Missing `facebook_id`')