loading...

re: Nested Conditional Operators VIEW POST

FULL DISCUSSION
 

I would format it like this:

const validateInput = ({ field1, field2, field3 }) =>
  !field1
    ? Promise.reject('Missing field1')
    : !Array.isArray(field2)
      ? Promise.reject('field2 is not an array')
      : !isValidType(field3)
        ? Promise.reject('field3 is invalid')
        : Promise.resolve()

To my disappointment, Prettier does exactly that when used to format selection but flattens it when using format document. What gives?!
Disclaimer: it originally didn't get rid of the parentheses, but after I removed them it didn't reinsert them.

However, you are messing around with Promises every single return here, so maybe the real solution here is the an async function?

const validateInput = async ({ field1, field2, field3 }) => {
  if (!field1) throw "Missing field1"
  if (!Array.isArray(field2)) throw "field2 is not an array"
  if (!isValidType(field3)) throw "field3 is invalid"
}

Wow, this is amazing :O And shorter! And will produce less diffs on refactoring!

However, do we actually need to return promises? Surely not!

const validateInput = ({ field1, field2, field3 }) => {
  if (!field1) return "Missing field1"
  if (!Array.isArray(field2)) return "field2 is not an array"
  if (!isValidType(field3)) return "field3 is invalid"
}

// we can get a promise later if we really need to
const asyncValidateInput1 = async obj => {
  const errStr = validateInput(obj)
  if (errStr) throw errStr
}
// and your conditional operators approach
const asyncValidateInput2 = obj => {
  const errStr = validateInput(obj)
  return errStr ? Promise.reject(errStr) : Promise.resolve()
}

But do we ever? Nah.

const assertInput = obj => {
  const errStr = validateInput(obj)
  if (errStr) throw errStr
  return obj
}

getObj.then(assertInput).then(/* safely use `obj` here */)

If someone actually reads this long-azz comment, yes, you should usually wrap what you're rejecting with into a new Error(str), for instance in the assertInput func, but this might be an acceptable exception.

Code of Conduct Report abuse