javascript - 如何处理异步循环函数中的await调用-nodejs

标签 javascript node.js asynchronous fs

我正在使用 CSV 解析器 npm 模块读取 CSV,并且必须对从 CSV 获取的数据(每行)执行一些操作。

const readstream = fs.createReadStream('src/working_file.csv');
const stream = readstream.pipe(parser());
  stream.on('data', async data => {
  // data is a JSON object of the row in CSV. 
  // Now i am calling another async function from user using the data in the JSON
  console.log('before calling');
  const writeToFile = await getImage(data.searchKey);
  console.log('after calling');
  // do other stuff
}

async function getImage(searchKey){
// im doing web scraping here using puppeeter
// it has some await calls too
console.log('in getimage');
 const results = await scrapper.run().catch(err => {
 console.error(err);
 process.exit(1);
 });
}

假设我的 csv 有 2 行,我的输出如下所示

before calling
in getimage
before calling
in getimage
after calling
after calling

但是当我这样做时,尽管我使用了等待,但所有调用都会同时发生。如果 CSV 中有 10 行,则调用该函数的所有 10 行都会同时发生。但我希望它一一发生。仅当第一行的操作完成时,我才需要操作第二行。

我的问题是所有调用都是同时发生的,而不是一个接一个地发生。

最佳答案

试试这个代码。

var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');

var inputFile='src/working_file.csv';

var parser = parse({delimiter: ','}, function (err, data) {
  async.eachSeries(data, function (line, callback) {
    // do something with the line
    doSomething(line).then(function() {
      // when processing finishes invoke the callback to move to the next one
      callback();
    });
  })
});
fs.createReadStream(inputFile).pipe(parser);

您还可以使用fast-csv

关于javascript - 如何处理异步循环函数中的await调用-nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53298211/

相关文章:

javascript - 异步加载脚本

node.js - Azure 应用程序服务上的 NodeJS 应用程序的持久应用程序日志

mysql - Node、Express、MYSQL 从 MYSQL 检索 JSON

javascript - <div id ="fb-root"和 JS 的最佳位置在哪里?

Python cmd 模块 - 异步事件后恢复提示

javascript - 将对象返回到node.js中的async.each函数中

javascript - beforeShowDay 每天调用两次

javascript - Angular 2 ES6/7 Eventemitter 更新其他组件

javascript - 使用javascript读取Json文件数据?

Javascript 日期添加一个月