【问题标题】:reading two csv files at a time with promises nodejs使用承诺 nodejs 一次读取两个 csv 文件
【发布时间】:2018-05-03 05:38:07
【问题描述】:

我不熟悉承诺。我想使用 Promise 一次读取两个 csv 文件。如何并行读取 2 个 csv 文件,然后进行链接。我已经浏览了this,但他们使用了一些名为 RSVP 的库。任何人都可以在不使用任何库函数的情况下帮助我如何做到这一点。我想一次读取 2 个文件,并且应该能够在下一个 .then() 访问这两个文件?

file = require('fs')

// Reading file
let readFile =(filename)=>{
    return new Promise(function(resolve, reject){
        file.readFile(filename, 'utf8', function(err, data){
            if(err){
                reject(err)
            }else{
                resolve(data)
            }
        });
    });
}



// Get the match id for season 2016
getMatchId=(matches)=>{
    let allRows = matches.split(/\r?\n|\r/);
    let match_id = []
    for(let i=1; i<allRows.length-1; i++){
        let x = allRows[i].split(',')
        if(x[1] === '2016'){
            match_id.push(parseInt((x[0])))
        }
    }
    return match_id
}



//  Final calculation to get runs per team in 2016
getExtraRunsin2016=(deliveries, match_id)=>{
    let eachRow = deliveries.split(/\r?\n|\r/);
    result = {}
    let total = 0
    for(let i=1; i<eachRow.length-1;i++){
        let x = eachRow[i].split(',')
        let team_name = x[3]
        let runs = parseInt(x[16])
        let id = parseInt(x[0])
        if(match_id.indexOf(id)){
            total+=runs
            result[team_name] += runs
        }else{
            result[team_name] = 0
        }
    }
    console.log(result, total)
}



// Promise
readFile('fileOne.csv')
    .then((matchesFile)=>{
        return getMatchId(matchesFile)
    })
    .then((data)=>{
        readFile('fileTwo.csv')
        .then((deliveries)=>{
            getExtraRunsin2016(deliveries, data)
        })
    })
    .catch(err=>{
        console.log(err)
    })

【问题讨论】:

    标签: node.js ecmascript-6 es6-promise


    【解决方案1】:

    您可以Promise.all() 组合事物而不使用任何其他库

    "use strict";
    
    Promise.all([
      readFile('fileOne.csv'),
      readFile('fileTwo.csv'),
    ]).then((results) => {
      let [rawFileOneValues, rawFileTwoValues] = results;
    
      // Your other function to process them
    }).catch(err => {
      console.log(err)
    });
    

    【讨论】:

      【解决方案2】:

      你想使用Promise.all()

      // Promise
      Promise.all([
        readFile('fileOne.csv').then(getMatchId),
        readFile('fileTwo.csv'),
      ])
        .then(([data, deliveries]) => getExtraRunsin2016(deliveries, data))
        .catch(err => console.log(err));
      

      我还建议使用fs-extra,它将取代您的readFile 实现。

      【讨论】:

        猜你喜欢
        • 2017-02-25
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        • 2023-04-09
        • 2018-01-19
        • 2021-11-19
        • 2023-01-14
        相关资源
        最近更新 更多