第一次推动自己在一个小型Node项目上使用Ramda,而且我已经遇到了困难。如何用Ramda编写下面的代码?
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 :(得分: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));
答案 1 :(得分:1)
如果您使用的是节点v.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)