javascript - Should an async API ever throw synchronously? -


I am writing a JavaScript function which makes an HTTP request and gives a promise for the result (but this question is its A callback-based implementation applies equally to).

If I know immediately that the arguments given for the function are invalid, then the function throw should be synchronously, or it should return a disapproved promise (or, if you wish , Then start the callback with the error example]?

It is important that an async function should be treated always in an async manner, special For the status of error from the form?

For example:

  Is it OK that  throw < / code> If you know that the program is not in a suitable position for the async operation to proceed?    getUserById (userId, cb) {if (userId! == parseInt (userId) }} {New error ('userId is not valid')} // make async call} // OR ... function getUserById (userId, cb) {if (userId! == parseInt (userId)} {return cb (new Error ('userId is not valid'))} // async call}    

Finally The decision to throw or not to sync is dependent on you, and you will be able to meet those people, on both sides Let's argue. The important thing is to maintain consistency in the documentation and behavior in practice.

On my case, my opinion is that your second option - the error in the callback is passing - seems more beautiful. Otherwise, you end up with the code looking like this:

  try {getUserById (7, function) {if (response.isSuccess) {// success case} other {// Case of failure}}); } Hold (error) {// other failure case}   

The control flow here is a bit confusing.

It looks like a single if / else if / else structure is in callback and around try / catch .

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -