Should a Javascript function avoid reject a promise via a ternary condition?

233 Views Asked by At

I saw a piece of code that looks funny to me. It feels like there are multiple things wrong here. Am I seeing a ternary here returning an error rather than a value? Shouldn't this therefore be an if-else?

const aData = await response.json();
return await new Promise((resolve, reject) => {
  (aData.title === aName)
    ? resolve('A data was found')
    : reject(new Error('Incorrect data was returned'));
});
1

There are 1 best solutions below

1
Bergi On BEST ANSWER

Both resolve and reject just return the value undefined, and your callback function doesn't return anything at all. Using a ternary operator to make it a single expression is rather useless.
For clarity, you should better write

if (aData.title === aName) resolve('A data was found');
else reject(new Error('Incorrect data was returned'));

although really you shouldn't be using the new Promise constructor here at all. Just

const aData = await response.json();
if (aData.title !== aName) throw new Error('Incorrect data was returned');
else return 'A data was found';