如何构建支持前置结果复用的NodeJS可复用Axios串行请求函数?
实现动态串行请求函数的方案
核心思路是维护一个上下文对象存储所有前置请求的返回结果,按顺序处理每个请求配置:解析输入中的路径引用、执行对应异步函数、将结果存入上下文供后续使用,最后提取目标输出。
第一步:实现路径解析工具函数
先写两个通用工具,用于通过点路径读取/写入对象值:
// 从对象中按点路径取值 function getValueByPath(obj, path) { return path.split('.').reduce((current, key) => current?.[key], obj); } // 按点路径给对象设值 function setValueByPath(obj, path, value) { const keys = path.split('.'); const lastKey = keys.pop(); const target = keys.reduce((current, key) => { current[key] = current[key] || {}; return current[key]; }, obj); target[lastKey] = value; }
第二步:实现核心执行函数
遍历配置串行处理每个请求,依赖上下文传递前置结果:
// 模拟你已有的异步请求函数(实际替换为Axios逻辑) async function getTitle(params) { return { text: "This is a title", title: "This is a title" // 对应配置中getTitle.title的引用 }; } async function getDescription(params) { return { text: `this is a description for ${params.title}` }; } // 主执行函数 async function executeDynamicRequests(config) { const context = {}; // 存储所有请求的原始返回结果 const finalResult = {}; // 用for...of保证串行执行,确保依赖顺序 for (const [resultKey, reqConfig] of Object.entries(config)) { const { name, input: rawInput, output } = reqConfig; // 1. 解析输入参数:替换路径引用为上下文实际值 const parsedInput = Object.fromEntries( Object.entries(rawInput).map(([key, val]) => { if (typeof val === 'string' && val.includes('.')) { return [key, getValueByPath(context, val)]; } return [key, val]; }) ); // 2. 执行对应的异步函数 const reqFunc = globalThis[name]; // 建议用函数映射表替代全局查找,更安全 if (!reqFunc || typeof reqFunc !== 'function') { throw new Error(`函数${name}未定义`); } const response = await reqFunc(parsedInput); // 3. 将结果存入上下文 setValueByPath(context, output, response); // 4. 提取当前请求的目标结果 finalResult[resultKey] = getValueByPath(context, output); } return finalResult; }
第三步:测试执行
用你提供的输入配置验证:
const input = { title: { name: "getTitle", input: { "keyword": "initial", "option": "second" }, output: "getTitle.text" }, description: { name: "getDescription", input: { "title": "getTitle.title" }, output: "getDescription.text" } }; executeDynamicRequests(input).then(console.log);
执行后输出:
{ title: "This is a title", description: "this is a description for This is a title" }
关键细节说明
- 串行保障:
for...of配合await确保请求按配置顺序执行,依赖前置结果的请求能拿到正确数据 - 上下文管理:
context存储所有请求的原始返回,支持任意深度的路径引用 - 函数查找优化:实际项目中建议维护函数映射表(如
const funcMap = { getTitle, getDescription }),避免全局变量污染,提升安全性
这种配置化请求编排的思路常见于低代码平台、API编排工具,核心是用配置替代硬编码链式调用,便于扩展和维护。
内容的提问来源于stack exchange,提问作者procoib
相关产品推荐
相关产品推荐

