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

编程入门 行业动态 更新时间:2024-10-04 13:32:41

重用<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数而不是编写新函数。只改变 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
});

更多推荐

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

本文发布于:2024-05-30 11:42:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770459.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!