如何在nodejs的readline.on
函数下使用await函数
我正在尝试使用readline.on
函数读取每一行,并且在从文件中读取每一行之后,我正在尝试将每一行数据传递给其他函数(它是第三方api),因此我为该函数编写了promise因此请在readline.on
函数下使用await来调用该函数,但不会从该函数返回结果。谁能帮我解决这个问题。预先感谢。
"use strict";
import yargs from 'yargs';
import fs from 'fs';
import redis from 'redis';
import path from 'path';
import readline from 'readline';
const args = yargs.argv;
// redis setup
const redisClient = redis.createClient();
const folderName = 'sample-data';
// list of files from data folder
let files = fs.readdirSync(__dirname + '/' + folderName);
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
};
async function getContentFromEachFile(filePath) {
return new Promise((resolve, reject) => {
let rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
resolve(rl);
});
};
async function readSeoDataFromEachFile() {
await asyncForEach(files, async (file) => {
let filePath = path.join(__dirname + '/' + folderName, file);
let rl = await getContentFromEachFile(filePath);
rl.on('line', async (line) => {
let data = performSeoDataSetUpProcess(line);
console.log(JSON.stringify(data.obj));
let result = await getResultsFromRedisUsingKey(data.obj.name);
console.log("result" + JSON.stringify(result));
});
});
};
async function getResultsFromRedisUsingKey(key) {
return new Promise((resolve, reject) => {
redisClient.get(key, function (err, result) {
if (err) {
resolve(err);
} else {
resolve(result);
}
});
});
};
readSeoDataFromEachFile();
答案 0 :(得分:1)
您的函数asyncForEach
和asyncForEach
中的getContentFromEachFile
调用的回调不会返回承诺,因此您不能将其与异步/等待功能一起使用。
getContentFromEachFile()
不需要异步/等待
结果,我会这样做:
function asyncForEach(array, callback) {
return new Promise(async (resolve, reject) => {
let result = []
array.forEach((file, index, files) => {
// concat the callback returned array of each file into the result
const res = await callback(file, index, files);
result = result.concat(res);
});
return resolve(result);
});
};
function getContentFromEachFile(filePath) {
return readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
};
async function readSeoDataFromEachFile() {
return await asyncForEach(files, (file) => {
return new Promise((resolve, reject) => {
const filePath = path.join(__dirname + '/' + folderName, file);
let callbackResult = [];
const rl = getContentFromEachFile(filePath);
rl.on('line', async (line) => {
let data = performSeoDataSetUpProcess(line);
console.log(JSON.stringify(data.obj));
// add the result from redis into the generated data
data.redisResult = await getResultsFromRedisUsingKey(data.obj.name);
console.log("result" + JSON.stringify(data.redisResult));
// store the result in the local variable
callbackResult.push(data);
});
rl.on('close', () => {
// finally return the stored result for this file
return resolve(callbackResult);
});
});
});
};
console.log(readSeoDataFromEachFile());