Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading