CSV阅读和使用输出,异步使用数据时出错

8mmmxcuj  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(122)

我正在尝试读取一个CSV文件,并使用它的数据来计算三明治的成本。我很挣扎,因为在第一次我是这样做的:

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);
   });

我试图存储返回的条目,但没有得到正确返回的值,但它将正确的输出记录到控制台。然后我看到下面是正确的方法。但是,我不能将下面存储为变量,因为我不能在顶层使用wait。我如何解决这个问题?

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()
x8goxv8g

x8goxv8g1#

由于方法storeSandwiches返回一个promise并且是一个异步操作,因此需要使用awaitthen来实现结果。
因此,您的代码将更改为:

等待:

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

带有then/catch

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

阅读更多关于promise的信息,here

相关问题