如何在 node js 中的 readline.on 函数下使用 await 函数



如何在nodejs上的readline.on函数下使用await函数我正在尝试使用 readline.on 函数读取每一行,从文件中读取每一行后,我尝试将每一行数据传递给其他某个第三方 api 函数,所以我为该函数编写了承诺,因此在函数下使用 await 调用该函数readline.on但它没有从该函数返回结果。任何人都可以帮我解决这个问题。提前谢谢。

"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();

你的函数asyncForEachasyncForEach调用的回调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());

最新更新