我有一个文件,该文件由line-by-line
npm包逐行读取。
我想将每行存储在数据库中(如果该行符合我的条件..)。
我想异步存储它,而且还要等到对数据库的所有保存操作完成之后,再继续执行下一个操作。
这是我目前的代码:
const fs = require('fs');
const path = require('path');
const LineByLineReader = require('line-by-line');
const moment = require('moment');
const saveFunc = async (filePath) => {
const savePromises = [];
const LBLR = new LineByLineReader(filePath);
LBLR.on('error', (error) => {
throw (error);
});
LBLR.on('line', async (line) => {
let lineJSON;
try {
lineJSON = JSON.parse(line);
} catch (e) { } // Just skip the line if cannot be parsed
if (!!lineJSON && 'caseId' in lineJSON && 'timestamp' in lineJSON && 'message' in lineJSON) {
if (lineJSON['message'] === "Socket.io 'connection' event") {
const logDateString = (lineJSON['timestamp'].split(' '))[0];
const logTimestamp = moment(logDateString, 'DD-MM-YYYY').toDate();
savePromises.push(new LivenessLog({
caseId: lineJSON['caseId'],
eventName: 'connect',
timestamp: logTimestamp,
}).save());
}
}
});
await new Promise((resolve) => {
LBLR.on('end', resolve);
});
await Promise.all(savePromises);
}
await saveLivenessLogs('..'); // X OPERATION -- !! --
因此,基本上,我希望.save()
操作能够立即执行(当前不会,因为我将其promise推送到了数组,因此只能在执行Promise.all([...])
时执行)。但是我也想仅在所有X OPERATION
个操作都成功执行后才返回到.save()
。
答案 0 :(得分:0)
您需要在.then
之后使用.save()
,以便立即执行(您想要的异步行为)
但是同时我们需要将结果承诺发送到savePromises
数组,以便您可以在Promise.all
的末尾使用它,以确认所有查询都已运行。
请尝试这样的操作。
savePromises.push(new LivenessLog({
caseId: lineJSON['caseId'],
eventName: 'connect',
timestamp: logTimestamp,
}).save().then(data => { return data; }));