我正在尝试读取一个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()
1条答案
按热度按时间x8goxv8g1#
由于方法
storeSandwiches
返回一个promise并且是一个异步操作,因此需要使用await
或then
来实现结果。因此,您的代码将更改为:
等待:
带有then/catch:
阅读更多关于promise的信息,here。