我利用nodejs在,批量请求一个接口并处理返回的数据。先要从excel里读取1000个身份证,然后通过请求接口得到返回数据,全部请求完后,将返回的数据存入excel并导出。现在我想问怎么批量请求1000次,最快?请求用的是superagent插件。我的语句里面有很多promise的方法,对应的不同接口,要求是每个身份证都跑一遍接口,获得的数据根据身份证统一整理
10条回答 默认 最新
- 社区专家-Monster-XH 2023-02-10 16:00关注
const superagent = require('superagent'); const exceljs = require('exceljs'); function getData1(id) { return new Promise((resolve, reject) => { superagent .get(https://example.com/api/data1/${id}) .then(res => { resolve(res.body); }) .catch(err => { reject(err); }); }); } function getData2(id) { return new Promise((resolve, reject) => { superagent .get(https://example.com/api/data2/${id}) .then(res => { resolve(res.body); }) .catch(err => { reject(err); }); }); } function getData3(id) { return new Promise((resolve, reject) => { superagent .get(https://example.com/api/data3/${id}) .then(res => { resolve(res.body); }) .catch(err => { reject(err); }); }); } async function processBatch(ids, startIndex) { // 为每个身份证号码发送请求 const data = await Promise.all( ids .slice(startIndex, startIndex + 10) .map(async id => { const [data1, data2, data3] = await Promise.all([ getData1(id), getData2(id), getData3(id) ]); return { id, data1, data2, data3 }; }) ); // 将数据写入 Excel data.forEach(d => { sheet.addRow([d.id, d.data1, d.data2, d.data3]); }); } async function main() { const workbook = new exceljs.Workbook(); const sheet = workbook.addWorksheet('Sheet 1'); // 读取 Excel 文件中的身份证号码 const ids = // ... let startIndex = 0; while (startIndex < ids.length) { await processBatch(ids, startIndex); startIndex += 10; } await workbook.xlsx.writeFile('output.xlsx'); } main();
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用
悬赏问题
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么