Reputation: 247
Im trying to understand something regarding JS standards:
When writing an async function or any function that returns any kind of promise I need to assume that the user of this function will want to catch the rejection and not to expect a boolean value in the resolve:
Good:
doSomething = async () => {
...
if (failed)
reject(error)
resolve("yay")
}
try {
await doSomething()
console.log("yay worked")
}
catch (error){
}
Bad:
doSomething = async () => {
...
if (failed)
resolve(false)
resolve(true)
}
didWork = await doSomething()
if (didWork){
console.log("yay")
else {
}
But my question is regarding non-async functions, is returning true/false as indicator as a success/failure considered a bad habit? any other good way to indicate success/failure? Also, tell me if my assumption above above good habits regarding promises is right in your eyes.
Thank you!
Upvotes: -1
Views: 1409
Reputation: 522577
It's the same for async and non-async functions really:
true
/false
can be a legitimate answer to the posed questionFor example, if the purpose of your function is to determine whether a string is numeric, the return values true
and false
have an obvious meaning. However, if you're passing in an object, which isn't a string to begin with, an exception is appropriate since the answer to the question "is this string numeric" for an object is "mu" 🤷♂️.
For an async function the same holds true: if it takes a network request to get a true
/false
answer for some question, then resolving the promise with true
/false
is entirely cromulent; e.g. if you're checking with the server whether an entered user name is still available, "yes" and "no" are valid answers. If the network request itself fails however, that would be an exceptional failure, a "mu", which you need to signal by rejecting the entire promise.
A promise rejection is just an asynchronous exception; with the await
syntax it is even handled the same as a synchronous exception. An exception is used for exceptional events, when a normal answer cannot be provided due to circumstances beyond the normal happy path.
Upvotes: 1