能否创建返回多个API调用结果数组的函数?替代逐次调用写法
如何通过JSON配置批量调用API并返回结果数组?
当然可以!这种通过配置化方式批量管理异步API调用的需求非常实用,我来帮你实现这个自定义函数MyFunc,完美匹配你的需求。
问题回顾
你之前的写法是逐个调用API并手动赋值变量:
var func1; var func2; var func3; apicall1().then((res) => { func1 = res; }); apicall1("string").then((res) => { func2 = res; }); apicall1(int).then((res) => { func3 = res; });
现在希望通过一份JSON配置定义所有要调用的函数和参数,然后用MyFunc一次性返回所有API调用的结果数组。
实现方案
核心思路是解析JSON配置 + 并行执行异步调用 + 统一返回结果,具体代码如下:
1. 先模拟API调用函数(用于测试)
// 模拟你的API调用函数,实际项目中替换为真实API function apicall1(args) { return new Promise(resolve => { setTimeout(() => resolve(`apicall1 结果: ${args ?? '无参数'}`), 100); }); } function apicall2(args) { return new Promise(resolve => { setTimeout(() => resolve(`apicall2 结果: ${JSON.stringify(args)}`), 100); }); }
2. 实现自定义函数MyFunc
async function MyFunc(jsonConfig) { // 解析JSON配置字符串为JS对象 const config = JSON.parse(jsonConfig); // 遍历配置项,生成对应的Promise列表 const promiseList = config.functions.map(item => { // 获取目标函数(假设函数在全局作用域,可根据实际场景调整作用域) const targetFunc = window[item.name]; if (!targetFunc) { throw new Error(`函数 ${item.name} 不存在,请检查配置`); } // 处理参数:适配null、单个值、数组参数三种情况 const args = item.args === null ? [] : Array.isArray(item.args) ? item.args : [item.args]; // 调用函数并返回Promise return targetFunc.apply(null, args); }); // 等待所有异步调用完成,返回结果数组 return Promise.all(promiseList); }
3. 调用示例
// 你的JSON配置(注意实际使用时可以直接用JS对象,不需要转字符串) const jsonConfig = `{ "functions": [ { "name": "apicall1", "args": null }, { "name": "apicall2", "args": "string" }, { "name": "apicall2", "args": [0, "string"] } ] }`; // 调用MyFunc获取结果 MyFunc(jsonConfig) .then(result => { console.log('所有API调用结果:', result); // 输出示例: ["apicall1 结果: 无参数", "apicall2 结果: \"string\"", "apicall2 结果: [0,\"string\"]"] }) .catch(err => { console.error('批量调用出错:', err); });
关键细节说明
- 并行执行:用
Promise.all让所有API调用并行执行,比逐个then的串行方式效率更高 - 参数适配:处理了
args为null(无参数)、单个值、数组三种常见场景,适配不同API的参数需求 - 错误处理:加入了函数存在性检查,避免因配置错误导致的静默失败
内容的提问来源于stack exchange,提问作者Amaury Laroze
相关产品推荐
相关产品推荐

