【发布时间】:2020-04-17 19:33:35
【问题描述】:
我正在解析 CSV 并处理每条记录以使用 Mongoose 将其插入到我的 MongoDB 中。我已经正确地从 CSV 中得到了一个数组,但是当我开始使用 forEach(和 async/await)对其进行迭代时,它就停在那里了。
这是我的代码:
const csv = require('csv-parser');
const fs = require('fs');
const Customer = require('../../app/models/Customers');
const projects = [];
const processRecords = async () => {
try {
const usableProjects = projects.filter((project) => project['cust_number customer']);
const customerNames = [...new Set(usableProjects.map((item) => item['Parent Name']))];
await customerNames.forEach(async (customerName) => {
console.log('Point 1');
const existingCustomer = await Customer.find({Name: customerName});
console.log('Point 2'); //<======= THIS CODE IS NEVER REACHED
if (existingCustomer.length > 0) {
console.log(`${customerName} already exists. Skipping...`);
return;
}
const customerRecord = usableProjects.find((project) => project['Parent Name'] === customerName);
const newCustomer = {
Name: customerName,
Source: 'CSV',
Initials: customerRecord.Initials,
Code: customerRecord.Codename,
};
const newCustomerRecord = await Customer.create(newCustomer);
if (newCustomerRecord) {
console.log(`Customer ${newCustomerRecord._id} created`);
}
});
} catch (err) {
console.log(err);
}
};
fs.createReadStream('customer_table.csv')
.pipe(csv())
.on('data', async (data) => projects.push(data))
.on('end', async () => {
processRecords();
});
这是输出:
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
我知道这可能与我未处理的同步/异步代码有关。但我无法修复它。提前致谢。
【问题讨论】:
-
array forEach 不返回 Promise,所以
awaiting 它不会做你想做的事 - 最简单和最简洁的解决方案是使用常规 for 循环而不是 forEach - 但是,这可能不解释为什么Customer.find永远不会解决 - 但这是朝着正确方向迈出的一步 -
这能回答你的问题吗? Using async/await with a forEach loop
标签: javascript node.js mongodb mongoose async-await