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

标签 javascript node.js ecmascript-6 es6-promise

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

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

最佳答案

你的函数asyncForEach以及你的 asyncForEach 的回调调用getContentFromEachFile不返回 promise ,因此您不能将其与 async/await 函数一起使用。

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

关于javascript - 如何在node js中的readline.on函数下使用await函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54397430/

相关文章:

javascript - 获取异步函数返回的数据

node.js - 为什么 req.params 返回 'undefined' ?

javascript - linux node.js 中的意外标识符 "let"

import - ES6 简写导入

javascript - d3 v4 中的中心和旋转投影

javascript - 使用 AngularJS 获取 Firebase 数据库中的父值和子值

javascript - ng-包括 : How can I maintain data in $scope after changing views?

node.js - Swagger 3.0.1 服务器生成器

jquery - 将 $.Deferred 替换为纯 JavaScript Promise

javascript - 根据值更改的时间将数组拆分为更小的数组