最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin42浏览0评论

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

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

我正在使用 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
块总是不同的。

这可能吗?

回答如下:

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

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
});
发布评论

评论列表(0)

  1. 暂无评论