【发布时间】:2021-03-02 17:33:12
【问题描述】:
我的问题是我必须从 CSV 文件中提取数据,向 MySQL 数据库发出 GET 请求(通过环回),并根据答案发出 Post 请求或不更新实例。
CSV 文件的导入工作正常,当我开始循环它并进行 API 调用时,所有的 GET 请求都是一个接一个地发出,而没有解决任何一个。
性能不是问题,因为它是一个只需要运行一次的导入器。所以我想我正在考虑的行为是一个队列:
- CSV 中的条目位于对象数组中
- 一次取一个对象
- 发出 GET 请求
- 等待回复
- 发出帖子请求
- 等待回复
- 从数组中取出下一个对象
这是最简单的方法吗?如果是这样,如何实现这种顺序行为?
我是后端开发的新手,所以这让我很困惑。
这是我的代码:
编辑
我现在正在使用 axios,但是我仍然收到错误:
ERROR: connect ECONNRESET 127.0.0.1:1338
当有很多并行获取请求时会出现该错误。我该如何解决这个问题?
const createSan = () => {
const data = fs.readFileSync(path.join(__dirname, '..', 'dist', 'test_mid.csv'), { encoding: 'utf8' });
var options = {
delimiter: ';', // optional
quote: '"' // optional
};
const json = csvjson.toObject(data, options);
json.forEach(item => {
if (item['BDBNR'].length > 0) {
let sanNr;
let sanPartOne;
let sanPartTwo;
let sanPartThree;
if (item['BDB_SORTENTEXT_NR'].length === 5) {
sanPartOne = (item['BDB_SORTENTEXT_NR']);
} else {
failedCount++;
return new Error('BDB_SORTENTEXT_NR incorrect');
}
if (item['SAN_MITTE'].length === 12) {
sanPartTwo = item['SAN_MITTE'];
} else if (item['SAN_MITTE'].length === 0) {
sanPartTwo = '000000000000';
} else {
failedCount++;
return new Error('SAN_Mitte incorrent');
}
if (item['SAN_ENDE'].length === 12) {
sanPartThree = item['SAN_ENDE'];
} else if (item['SAN_ENDE'].length !== 12) {
sanPartThree = item['SAN_ENDE'];
for (let i = sanPartThree.length; i < 12; i++) {
sanPartThree = '0'.concat(sanPartThree);
}
}
sanNr = sanPartOne + sanPartTwo + sanPartThree;
if (sanNr.length !== 29) {
failedCount++;
return new Error('SAN Nummer incorrect');
}
const getData = async () => {
try {
const res = await axios.get(`http://localhost:1338/api/articles?filter={"where":{"bdbnr":"${item['BDBNR']}"}}`)
postCall(res.data);
} catch(err) {
console.log(err)
}
}
getData();
const postCall = data => {
if (data.totalRowCount > 0 && data.rows[0]) {
if (data.rows[0].bdbnr.length > 0) {
data.rows[0].bdbnr = sanNr;
data.rows[0].tstamp = 1;
data.rows[0].crdate = 1;
data = data.rows[0];
const postData = async() => {
try {
console.log('fired')
const res = await axios.post(`http://localhost:1338/api/articles/${data.id}/replace`, data)
.then(res => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
})
} catch(err) {
console.log(err)
}
}
postData();
}
}
}
}
})
}
createSan();
非常感谢帮助
【问题讨论】:
-
您不能一次加载整个文件。看看流(例如stackoverflow.com/a/50487888/4480179)。另外,imports 应该在文件的顶部,不要把 require('http') 放在
map循环中 -
感谢您的评论。抱歉,也许我没有说清楚,CSV 的导入工作正常,问题是 API 调用(它一个接一个地运行所有 GET 请求,没有解决任何问题)。 CSV 文件的流可以帮助我吗?
标签: node.js api asynchronous post get