If you come from start of Node.js, you probably remember that the callback functions had always by convention a error as it's first parameter and the result as the second one.
Now days, most people use async functions instead of callbacks because they leave the code more clean and are usually easier to understand by someone that comes from programming in other languages.
In my opinion, a problem that exists when using async functions is the error handling. Usually people use try / catch blocks but there is a better way i will show you now.
You could have a wrapper function or handler function that always return a pattern like in callback functions, this is, a error as first and a result as second parameter.
Take a look at the gist below so you could understand what i'm talking about:
I created a function that validates if the user input is the number one (1). If it's valid, it returns the message "OK" and if it's not, it returns the error message saying that the user must type (1).
Simply download the gist and type in your terminal:
node async_error_handling.js {value}
where value must be a number. To try the positive result, replace "value" with 1 and to try the error result, replace "value" with any other value than 1.
Now you could use the asyncHandler to handle you async/await calls.
Hope you enjoy!
Now days, most people use async functions instead of callbacks because they leave the code more clean and are usually easier to understand by someone that comes from programming in other languages.
In my opinion, a problem that exists when using async functions is the error handling. Usually people use try / catch blocks but there is a better way i will show you now.
You could have a wrapper function or handler function that always return a pattern like in callback functions, this is, a error as first and a result as second parameter.
Take a look at the gist below so you could understand what i'm talking about:
I created a function that validates if the user input is the number one (1). If it's valid, it returns the message "OK" and if it's not, it returns the error message saying that the user must type (1).
Simply download the gist and type in your terminal:
node async_error_handling.js {value}
where value must be a number. To try the positive result, replace "value" with 1 and to try the error result, replace "value" with any other value than 1.
Now you could use the asyncHandler to handle you async/await calls.
Hope you enjoy!
Comments
Post a Comment