【问题标题】:How to use await functions under readline.on functions in node jsnodejs中readline.on函数下如何使用await函数
【发布时间】:2019-01-28 07:38:55
【问题描述】:

如何在nodejs的readline.on函数下使用await函数 我正在尝试使用 readline.on 函数读取每一行,在从文件中读取每一行之后,我试图将每一行数据传递给第三方 api 的其他函数,所以我已经为该函数编写了承诺,所以调用该函数在 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();

【问题讨论】:

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


    【解决方案1】:

    您的函数 asyncForEach 和您在 getContentFromEachFile 中调用的 asyncForEach 回调不返回承诺,因此您不能将它与 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());
    

    【讨论】:

    • getContentFromEachFile 函数返回每个文件内容,但问题是无法从该函数调用 getResultsFromRedisUsingKey 结果
    • 你确定getResultsFromRedisUsingKey() 函数返回一个承诺吗?
    • 对不起,我没有在问题上添加 getResultsFromRedisUsingKey 函数,现在我添加了请再次检查问题。
    • data.objresult 登录了什么?
    • 谢谢@dun32 你帮了我很多
    猜你喜欢
    • 2019-06-22
    • 2019-02-17
    • 2020-08-01
    • 2022-01-27
    • 2020-07-29
    • 2023-02-06
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多