首页 > 解决方案 > 使用 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

我一直在查看这里的其他线程,只是没有点击我做错了什么。

标签: javascriptnode.jspromise

解决方案


为了使承诺起作用,您需要一个“异步根”,这是一个回调。由于您的函数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);
 });

推荐阅读