catch errors in async/await like a pro
The main reason of using async await is
- async await makes our code look like synchronous 🐼
- clean code 🧹
It definitely makes our code look synchronous. But does it really make our code clean? 🤔
Consider bellow code snippet where we have multiple try catch
block with await
functionality.
This is very similar to using then
block. The benefit of using async/await is not shining 🌟 in above code.
With time ⏲️ code in our project and so does the try catch blocks, and we can’t skip them as we have to handle errors in our application gracefully in order to make user experience smooth.
We have two possible ways to make our code look nice.
Way 1: Instead of having try catch
block as a separate block, we can simply catch
the error in same line along with await
.
Way 2: The Way makes our code little bit good, we have another way which makes our code look even more cleaner and gives a pro touch.
In this way we can have a handler function to have try catch
block, and we can import this function to make async
calls.
If we want to pass some parameters in `fetchDataFromServer` then we can leverage the functionality of currying in order pass params.
Please find the working code below:
Happy Coding !!!