如何使用TypeScript批量发送POST请求体?解决API大数据量限制
解决方案
1. 重构代码实现分批请求
先把原始字符串格式的请求体改成对象,方便拆分数组;新增数组分批工具函数,循环发送每批请求:
// 替换为你的实际大型数字数组 const largeNumberArray = [1,26,38,4,57,6,77,8,9,3333,55,3,55, ...]; // 根据API能处理的上限调整每批大小 const BATCH_SIZE = 10; // 数组分批工具函数 const chunkArray = (arr: number[], size: number): number[][] => { const chunks = []; for (let i = 0; i < arr.length; i += size) { chunks.push(arr.slice(i, i + size)); } return chunks; }; export class Test { async test1(): Promise<void> { // 把大数组拆分成多个小批次 const batches = chunkArray(largeNumberArray, BATCH_SIZE); // 串行发送每批请求(API允许并发的话,可改用Promise.all) for (const batch of batches) { const requestBody = { arrayOfNum: batch }; const response = await fetch(`${url}`, { method: 'POST', body: JSON.stringify(requestBody), headers: { 'Content-Type': 'application/json', 'Authorization': `key=${API_KEY}` } }); // 可选:校验请求是否成功,失败则抛出错误 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } console.log(`批次发送成功,当前批次长度:${batch.length}`); } } }
2. 处理调用时无法使用await的情况
因为通过npm run testFunc执行,直接调用async函数会有未处理Promise的风险,所以调用时添加错误捕获:
const test = new Test(); // 捕获请求过程中的错误,避免进程静默失败 test.test1().catch(err => { console.error('批量请求出错:', err); process.exit(1); // 出错时退出进程并返回错误码 });
关键提示
- 分批大小:
BATCH_SIZE要根据API的实际承载能力调整,比如单请求允许的最大数组长度 - 请求并发:如果API不限流,可把循环改成
await Promise.all(batches.map(batch => 发送请求逻辑)),提升效率 - 错误处理:必须添加错误捕获,否则进程可能在出错时无任何提示
内容的提问来源于stack exchange,提问作者Ruby
相关产品推荐
相关产品推荐

