我将csvReader与nestjs一起使用,并将'on'事件中的函数标记为异步,并将保存到DB标记为await。
'on' 事件似乎不会等待保存完成并在处理文件后打印日志消息。
代码如下所示:
const CsvReadableStream = require('csv-reader');
const Fs = require('fs');
const path = require('path');
@EntityRepository(UserTitle)
export class UserTitleRepository extends Repository<UserTitle> {
async seedUserTitle(): Promise<string> {
// load titles
const basePath = __dirname.replace('/dist', '');
const filePath = path.join(basePath, 'titles.csv');
let inputStream = Fs.createReadStream(filePath, 'utf8');
let numRecs = 0;
inputStream
.pipe(
new CsvReadableStream({
parseNumbers: true,
parseBooleans: true,
trim: true,
}),
)
.on('data', async function (row: SeedTitleDto) {
const seedTitle = new UserTitle();
seedTitle.shortName = row[0];
seedTitle.name = row[1];
seedTitle.seq = row[2];
try {
await seedTitle.save();
numRecs++;
console.log(`Save ${numRecs}`);
} catch (error) {
if (error.code === '23505') {
// duplicate username
throw new ConflictException(
`User Title ${seedTitle.shortName} already exists`,
);
return;
} else {
throw new InternalServerErrorException(error.message);
return;
}
}
})
.on('end', function async(row: SeedTitleDto) {
console.log(`End of file reached ${numRecs}`);
});
return `Created ${numRecs} titles`;
}
}
有谁知道如何让这个包允许异步处理?
非常感谢