javascript - 使用 Promise 确保文件流已经结束
问题描述
我从以下两个变量开始
var yearTotal2008 = 0;
var year2008TallyByPatient = {};
然后通读大 csv 文件的每一行,相应地更新两个变量。这需要一段时间。
const produceChartData = () => {
inputStream
.pipe(CsvReadableStream())
.on('data', function (row) {
if ((20080101 <= row[3]) && (row[3] <= 20081231)) {
yearTotal2008 += parseFloat(row[6])
yearPatientTally(year2008TallyByPatient, row[0], parseFloat(row[6]))
}
})
.on('end', function (data) {
console.log('end of the read')
console.log('year total claims: ' + yearTotal2008)
console.log('average claims by patient: ' + averageClaimByPatient(year2008TallyByPatient))
return;
})
}
我想确保流已经完成,并且所有相关值都已添加到这两个变量中。
function resolveGetCall (getCall) {
return Promise.resolve(getCall)
}
resolveGetCall(produceChartData())
.then(result => {
return Promise.resolve(averageClaimByPatient(year2008TallyByPatient))
})
.then(result => console.log(result))
输出是这样的
NaN
end of the read
year total claims: 125329820
average claims by patient: 2447.70
我一直在查看这里的其他线程,只是没有点击我做错了什么。
解决方案
为了使承诺起作用,您需要一个“异步根”,这是一个回调。由于您的函数produceChartData
不接受回调也不返回承诺,因此不能使用它。但它很容易添加:
const produceChartData = () => new Promise(resolve => { // return a promise and produce a callback
inputStream
.pipe(CsvReadableStream())
.on('data', function (row) {
if ((20080101 <= row[3]) && (row[3] <= 20081231)) {
yearTotal2008 += parseFloat(row[6])
yearPatientTally(year2008TallyByPatient, row[0], parseFloat(row[6]))
}
})
.on('end', function (data) {
console.log('end of the read')
console.log('year total claims: ' + yearTotal2008)
console.log('average claims by patient: ' + averageClaimByPatient(year2008TallyByPatient))
resolve({ yearTotal2008, year2008TallyByPatient }); // call back
})
});
可以用作:
produceChartData().then(({ yearTotal2008 }) => {
console.log(yearTotal2008);
});
推荐阅读
- javascript - Discord.js DM 成员静音时
- arrays - 如何将数组值传递给 TFDConnection.ExecSQLScalar?
- html - css + xhtml2pdf:每页只强制一个表格
- python - 有人可以帮助修复python中函数参数的代码吗
- python - python:通过单个对象访问列表列表中的元素
- python - python:字符的熵条件
- r - 从深度嵌套列表中提取数据
- javascript - 检测用户是否只第一次滚动
- javascript - 如何在javascript中自动关闭括号和大括号
- python - 同步 kafka 生产者发送仍然有 0 秒超时?