Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - Is returning true/false for a function as indicator for success/failure considered a good standard in JS?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's the same for async and non-async functions really:

  • true/false can be a legitimate answer to the posed question
  • an exception/promise rejection is a sign of a serious failure

For 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...