CSV reading and using output, error with using data asynchronously

52 Views Asked by At

I am attempting to read a CSV document and use its data to work out the cost of a sandwich. I am struggling as at first I was doing it as follows:

const entries = []

fs.createReadStream("./sandwiches.csv")
  .pipe(parse({ delimiter: ",", from_line: 2 }))
   .on("data", function (row) {
     entries.push(new Sandwich(row[0], row[1]));
   })
   .on("end", function () {
     return entries
   })
   .on("error", function (error) {
     console.log(error.message);
   });

I was attempting to store the returned entries but was not getting a value returned correctly, but it was logging the correct output to the console. I then saw that the below is the correct way to do it. However, I cannot store the below as variable, as I cannot use await at the top level. How do I get around this issue?

const fs = require("fs");
const { parse } = require("csv-parse");
const { finished } = require("stream/promises")

const storeSandwiches = async () => {
  const entries = [];

  const parser = fs
    .createReadStream("./sandwiches.csv")
    .pipe(parse({ delimiter: ",", from_line: 1 }));

  parser
    .on("readable", function () {
      let record;
      while ((record = parser.read()) !== null) {
        entries.push(new Sandwich(record[0], record[1]));
      }
    })
    // .on("end", function () {
    //   console.log("finished");
    // })
    .on("error", function (error) {
      console.log(error.message);
    });

  await finished(parser);
  return entries;
};

const sandwiches = await storeSandwiches()
1

There are 1 best solutions below

0
On

Since the method storeSandwiches returns a promise and is an asynchronous operation, you need to fulfill the result by using await or then.

So your code would be changed to like this:

with await:

(async () => {
  try {
    await storeSandwiches();
  } catch(error) {
    // handle error
  }
})();

with then/catch:

storeSandwiches().then((result) => {
  // any logic
}).catch((error) => {
  // handle error
})

read more about promise, here.