Search code examples
javascriptnode.jsfunctionecmascript-6try-catch

Reuse the function instead to writing new ones. Only change try block


I am using axios to write functions. The outside of the function is always the same. I want to be able to resuse the outside of my function and always change the try and catch blocks. Is there a way to do that?

My code:

const funcOne = async (arg) => {
  const result = await axios(arg); //axios post
  try {
    //try code
  } catch (e) {
    console.log(e);
  }
};

const funcTwo = async (arg1, arg2) => {
  const result = await axios(arg1);  //axios post
  try {
    //try code. arg2 used here
  } catch (e) {
    console.log(e);
  }
};

I will have many more such functions. Is there a way to write this part of the code just once and reuse:

const func = async (arg1, arg2) => {
  const result = await axios(arg1);  //axios post
  catch (e) {
    console.log(e);
  }
};

Only my try block is always going to be different.

Is this possible?


Solution

  • Introducing higher-order functions, you can return a function inside a function to kinda abstract it out:

    const higherOrderFunc = (fn) => {
      return async (arg1, ...args) => {
        const result = await axios(arg1);
        try {
          return fn(result, ...args);
        } catch (e) {
          console.log(e);
        }
      };
    };
    
    const func = higherOrderFunc((result) => {
      //try code
    });
    
    const func = higherOrderFunc((result, arg2) => {
      // Try code. arg2 used here
    });