Async Await try-catch hell ??????
Prasath Ravichandran
Software Engineer | JavaScript, React.js | Innovating with Cutting-Edge Technologies
There are many new features in JavaScript, which were helpful for the developer in day-to-day programming. One of them is Async/Await for handling asynchronous function and a cleaner way for handling promises.
Using Async/Await feels like heaven because it avoids the callback hell by writing asynchronous code in a clean line-by-line format.
But during error handling for Async/Await, we can end up with try-catch blocks, so all your beautiful one-liners expand to many lines of code??.
One of the easy ways to resolve this is to append the catch method to the end of each promise. It is better but still gets repetitive.
Another option is to standardize error handling, which means create a function that implements one try-catch block to replace the others. It first resolves the promise then returns an array where the first element is the data and the second element is the error, but if there is an error, then the data is null and, the error is defined.
When you call this function in your code, you can destructure it to get a clean one-liner with error handling.
If you have any other thoughts about the Async/Await or if you know any other techniques for handling promises and asynchronous functions, please put them in the comment box ??????
If you like the content, Please share this article with your friends.
Thanks for reading! Be safe at home!
Happy Coding.