我利用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 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
- ¥15 Windows11, backspace, enter, space键失灵