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.

Screenshot 2021-06-11 235825.png

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

Screenshot 2021-06-12 001052.png

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

Screenshot 2021-06-12 001413.png

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.

Screenshot 2021-06-12 002242.png

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.

Screenshot 2021-06-12 003029.png

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

Screenshot 2021-06-12 004151.png

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.

Β