Refactoring to Avoid Try and Catch Block in Promises
๐ค Why do we need this?
I like async...await
to handle promises but sometimes I don't like try...catch
block in linear coding in a function. Basically, I hate nesting...
๐ฅ Problems
- Extra number of lines
- Nesting code with extra variable declaration
// Main function
function onBoardingUser = async (accessToken: string) {
let user = null;
try {
const { data } = await getUserAccountDetails(accessToken);
user = data;
} catch (error) {
console.log({ error })
}
console.log({ user }) // User data
}
๐ค Did you notice? We had to declare a global variable to store user data into it because user data was being fetched inside the block scope. So we had to create and update user
to make it accessible at a global level
๐ Solution
Let's create a reusable function that will accept the callback function as a parameter and will perform
try...catch
operation in it and return both data and error object.// Resuable function import { AxiosResponse } from "axios"; export async function WrapIntoTryCatch(fn: () => Promise<AxiosResponse<{ data: any, error: any }>>) { try { const {data} = await fn(); return {data} } catch (error) { console.log({error}); return {error} } }
Let's use that function in the main function
function onBoardingUser = async (accessToken: string) { const { data, error } = await WrapIntoTryCatch(() => getUserAccountDetails(accessToken)); console.log({ data }) // User data }
๐ฏ Conclusion
// Before (10 number of lines with nesting and extra variable declaration)
function onBoardingUser = async (accessToken: string) {
let user = null;
try {
const { data } = await getUserAccountDetails(accessToken);
user = data;
} catch (error) {
console.log({ error })
}
console.log({ user }) // User data
}
// After (2 number of lines without nesting and extra variable)
function onBoardingUser = async (accessToken: string) {
const { data, error } = await WrapIntoTryCatch(() => getUserAccountDetails(accessToken));
console.log({ data }) // User data
}
That's it ๐๐ป
๐๐ฝ Hope you enjoyed it, comment section is open, you are welcome, let's communicate there ๐ค
ย