我是承诺的新手。我想使用promises一次读取两个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)
})
&#13;
答案 0 :(得分:0)
您想使用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
实施。
答案 1 :(得分:0)
您可以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)
});