函数而不是编写新函数。只改变 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 块
发布评论