loading...

re: Nested Conditional Operators VIEW POST

FULL DISCUSSION
 

I like using short-circuiting for things like that instead. With the nested ternary its hard to see what part is in what part.

function(field1, field2, field3) {
    field1 || Promise.reject('No field 1!')
    Array.isArray(field2) || Promise.reject('Field 2 is not an array!')
    isValidType(field3) || Promise.reject('Invalid field 3!')
}
 

But that function doesn't return anything, how do you get a return value?

 

I didn't actually read your function that carefully, but since it looks like it either rejects or does a Promise.resolve() then just at the end add return Promise.resolve() since nothing seems acted upon.

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.

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.

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.

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!

Code of Conduct Report abuse