如何复用Axios函数外层逻辑,仅自定义try代码块?
复用Axios异步函数的固定逻辑,自定义try代码块
问题描述
我用Axios编写异步函数时,外层逻辑(Axios请求、catch块打印错误)完全一致,只想自定义try代码块的内容。现有示例代码:
const funcOne = async (arg) => { const result = await axios(arg); //axios post try { //自定义try代码 } catch (e) { console.log(e); } }; const funcTwo = async (arg1, arg2) => { const result = await axios(arg1); //axios post try { //自定义try代码,会用到arg2 } catch (e) { console.log(e); } };
希望把以下固定逻辑只编写一次并复用:
const func = async (arg1, arg2) => { const result = await axios(arg1); //axios post catch (e) { console.log(e); } };
仅try代码块随需求变化,请问能否实现?
实现方案
当然可以实现,核心是通过高阶函数封装固定逻辑,将自定义的try代码作为回调传入。
方式一:直接调用的通用函数
// 封装通用处理逻辑 const handleAxiosRequest = async (axiosConfig, customHandler, ...extraParams) => { try { const result = await axios(axiosConfig); // 执行自定义的try代码,传入请求结果和额外参数 await customHandler(result, ...extraParams); } catch (e) { console.log(e); } }; // 创建第一个业务函数 const funcOne = async (arg) => { await handleAxiosRequest(arg, (result) => { // 这里写funcOne的自定义逻辑 console.log('处理funcOne的结果:', result.data); }); }; // 创建第二个业务函数 const funcTwo = async (arg1, arg2) => { await handleAxiosRequest(arg1, (result, arg2) => { // 这里写funcTwo的自定义逻辑,直接使用arg2 console.log('处理funcTwo的结果:', result.data, '额外参数:', arg2); }, arg2); };
方式二:返回业务函数的封装器
如果希望业务函数的调用方式更贴近原代码,可以让封装函数返回一个新的异步函数:
// 封装器:接收自定义处理逻辑,返回业务函数 const createAxiosFunc = (customHandler) => { return async (axiosConfig, ...extraParams) => { try { const result = await axios(axiosConfig); await customHandler(result, ...extraParams); } catch (e) { console.log(e); } }; }; // 创建业务函数 const funcOne = createAxiosFunc((result) => { // funcOne的自定义逻辑 }); const funcTwo = createAxiosFunc((result, arg2) => { // funcTwo的自定义逻辑,使用arg2 }); // 调用方式和原代码一致 funcOne('/api/user'); funcTwo('/api/order', '12345');
关键说明
- 两种方式都把Axios请求、错误捕获的固定逻辑抽离到了通用函数里,无需重复编写
- 自定义逻辑通过
customHandler回调传入,能直接获取Axios的请求结果和额外参数 - 新增业务函数时,只需要关注自定义的try代码块,其他逻辑自动复用
内容的提问来源于stack exchange,提问作者nb_nb_nb
相关产品推荐
相关产品推荐

