как обрабатывать ожидающие вызовы в функциях асинхронного цикла - nodejs - PullRequest
0 голосов
/ 14 ноября 2018

Я читаю CSV с помощью модуля CSV-анализатора npm и должен выполнить некоторую операцию с данными, полученными из 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

, но когда я делаю это, все вызовы происходят одновременно, хотя я использовал await.Если у меня есть 10 строк в CSV, все 10 строк, вызывающих функцию, происходят одновременно.но я хочу, чтобы это произошло один за другим.Только когда операция с первым рядом завершится, я хочу работать со вторым рядом.

моя проблема в том, что все звонки происходят одновременно, а не один за другим.

1 Ответ

0 голосов
/ 14 ноября 2018

Попробуйте этот код.

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

...