DEV Community

Discussion on: Nested Conditional Operators

 
avalander profile image
Avalander

I'm sorry but I still don't get how this is supposed to work. The statement field1 || Promise.reject(...) will not make the function return, so it will return Promise.resolve() every time.

I can see it working if you wrap the body in a new promise

const validateInput = ({ field1, field2, field3 }) => new Promise((resolve, reject) => {
  field1 || reject('Nope')
  Array.isArrat(field2) || reject('Double nope')
  resolve()
})

But I'm not sure this conveys the intent as clearly as a chained conditional operator or if statements.

Thread Thread
 
emgodev profile image
Michael • Edited

I like this much more than nested conditions. And if used appropriately, it's better than my example. It's important to find the right use for each situation.

Thread Thread
 
samuraiseoul profile image
Sophie The Lionhart

I didn't test my code at all and assumed we were doing a basic javascript styled pseudo-code thing here. My bad.

I assumed that basically what you just posted is what we had but we weren't showing the promise set up stuff, just the helper function. But yeah, the example you posted now is what I was going for more or less.

I think the nested ternary is super hard to read, and this is easier, though the use of the short-circuit like this is not a standard thing people do, I've found that people come to like it once they get used to it.

This all said, Typescript could remove the need for all the validation entirely.

Thread Thread
 
avalander profile image
Avalander

Javascript pseudocode is fine, I kept asking because I didn't understand the intent of your code, not because it didn't work.

But yeah, the validations are not important, what I wanted to discuss is the construct in general, my particular case was just an example, so thanks for your input!