重用函数而不是编写新函数。只改变 try 块

问题描述 投票:0回答:1

我正在使用 axios 编写函数。函数的外部总是相同的。我希望能够重新使用我的函数的外部,并始终更改

try
catch
块。有办法吗?

我的代码:

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);
  }
};

我会有更多这样的功能。有没有办法只写一次这部分代码并重用:

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

只有我的

try
块总是不同的。

这可能吗?

javascript node.js function ecmascript-6 try-catch
1个回答
1
投票

引入高阶函数,你可以在函数内部返回一个函数来抽象它:

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
});
© www.soinside.com 2019 - 2024. All rights reserved.