如何处理异步循环功能中的等待调用-nodejs

时间:2018-11-14 10:37:44

标签: 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

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

我的问题是所有呼叫都是一次发生,而不是一次发生。

1 个答案:

答案 0 :(得分:-1)

尝试此代码。

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