I have an objective to map through a list of json files, and map them into objects and return them in node.js, so far I have the following code:
function getDirFiles(dataFolder) {
return new Promise((resolve, reject) => {
let fileNames = [];
fs.readdir(dataFolder, (err, files) => {
if (err) {
console.log(err);
reject(err);
} else {
files.forEach(file => {
fileNames.push(file);
});
resolve(fileNames);
}
});
});
}
let data = []
getDirFiles(dataFolder).then(files =>{
files.forEach(async file =>{
const fileName = __dirname + '/parsed_json_data' + '/' + file
await fs.readFile(fileName , 'utf8', async function(err, data){
if(err) throw err;
data = await JSON.parse(data);
})
})
})
console.log(data) //return empty array like it was initialized
So first I return a promise, and call a .then()
to resolve the function, but since, the next operation is also async, I want to await, this operation, before the code proceeds. How can this be achieved, so that I can return the json from all the files?