Async Await try-catch hell ??????

Async Await try-catch hell ??????

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.

No alt text provided for this image

Using Async/Await feels like heaven because it avoids the callback hell by writing asynchronous code in a clean line-by-line format.

No alt text provided for this image

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

No alt text provided for this image

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.

No alt text provided for this image

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.

No alt text provided for this image

When you call this function in your code, you can destructure it to get a clean one-liner with error handling.

No alt text provided for this image

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.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了