繁体   English   中英

Nodejs拆分大数组并进行多个API调用

[英]Nodejs Split large array and make multiple API calls

我有一个 CSV 文件,其中包含 21k 条记录(1 字字母数字类型/行)。 我需要读取这些记录并将它们发送到 JSON 键值对格式的 API 以进行某些一次只接受 500 个元素的处理。 我有一个解决方案,但我想知道是否有更好或更有效的解决方案/算法?

算法:

  1. 将 CSV 加载到数组中
  2. 将此一维数组拆分为 N 数组,固定长度为 500 列(元素)
  3. 使用这 N 个 500 元素数组中的每一个,准备 JSON 有效负载并发送到 API。

代码:

var dataArray = [];

fs.readFile(inputPath, 'utf8', function (err, data) {
    dataArray = data.split(/\r?\n/);  
 })


var temp = [];
for(i=0;i<dataArray.length;){
  temp=[];
 for(j=0;(j<500 && i<dataArray.length);j++){  
    temp.push(data[i]);
    i++;
  }
  // make API call with current values of temp array
  makeCallToAPI(temp);
}

我会使用 lodash 或下划线_.chunk() 另请注意,fs 和 API 都可以更好地处理异步。

const _ = require('lodash');

async function callApi(chunk) {
  // return a promise that resolves with the result of the api
}

async function readFS(inputPath) {
  return new Promise((resolve, reject) => {
    fs.readFile(inputPath, 'utf8', function (err, data) {
      if (err) reject(err);
      else resolve(data.split(/\r?\n/));
    });
  });
}

async function doTheWork(inputPath) {
  const data = await readFS(inputPath);
  const chunks = _.chunk(data, 500)
  const promises = chunks.map(callApi)
  return _.flatten(Promise.all(promises));
}

还要注意_.flatten()的使用,因为最后一个 Promise.all() 将解析为一组 arrays 的承诺块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM