Refactoring to Avoid Try and Catch Block in Promises

ยท

2 min read

๐Ÿค” 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

  1. Extra number of lines
  2. 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

  1. 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}
     }
    }
    
  2. 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 ๐Ÿค

ย