2017-08-07 95 views
0

首次推动我自己在一个小型Node项目上使用Ramda,并且我遇到了困难。我如何用Ramda编写代码?使用Ramda从许多文件中收集JSON数据

const dataObject = {}; 
const promises = []; 

for (let i = 0; i < myTableNames.length; i++) { 
    const tableName = myTableNames[i]; 
    const newPromise = new Promise((resolve, reject) => { 
     fs.readFile(`./tables/${filename}.json`, (err, content) => { 
      if (err) { 
       return reject(); 
      } 
      dataObject[tableName] = JSON.parse(content); 
      return resolve(); 
     }); 
    }); 
    promises.push(newPromise); 
} 

Promise.all(promises).then(() => { 
    console.log(dataObject); 
}); 
+0

正在使用'https:// www.npmjs.com/package/fs-extra'选项吗?如果是这样,它会让事情变得更容易,因为'fs'方法返回promise。 – adrice727

回答

1

如果使用节点8节,你可以不喜欢这样。 Demo

// promisify fs.readFile 
const readFile = require('util').promisify(fs.readFile) 
const getFilePath = tableName => `./tables/${tableName}.json` 
const loadFileContents = pipe(getFilePath, pipeP(readFile, JSON.parse)) 

// 1. Map each table name into promise that resolves with 
// parsed file content 
// 2. Wait for all 
// 3. Build object using table names as keys and contents as 
// as values 
Promise.all(map(loadFileContents, myTableNames)) 
    .then(zipObj(myTableNames)) 
    .then(console.log) 
+0

两个很好的解决方案 - 我选择了这个,因为我从中学到了关于zipObj的知识。谢谢。 – ed94133

1

随着fs-extra

const fs = require('fs-extra'); 

const readFile = fileName => fs.readFile(`./tables/${fileName}.json`); 
const buildResults = (files) => { 
    const build = (acc, json, idx) => R.assoc(myTableNames[idx], JSON.parse(json), acc); 
    return R.reduce(build, {}, files); 
} 

Promise.all(R.map(readFile, myTableNames)) 
    .then(buildResults) 
    .then(data => console.log(data)); 
+0

这里有什么'resolve'和'reject'? –

+0

@ScottSauyet假设这将被封装在一个返回承诺的函数中。 – adrice727

+0

@ScottSauyet答案已更新。 – adrice727