I've got a function that reads date from files and stores them into an array. It is implemented asynchronously with async/await functionality.
The problem is that it is executing in the wrong order:
const util = require('util');
const fs = require('fs');
const path = require('path');
const readFile = util.promisify(fs.readFile);
const readDirectory = util.promisify(fs.readdir);
// Retrieve logs from logs files and store them into an array
const getAuditLogsData = async () => {
const logsFolderPath = path.join(__dirname, '../', 'logs');
const logData = [];
try {
const files = await readDirectory(logsFolderPath);
// 1ST - OK
console.log(files);
files.forEach(async (file) => {
const content = await readFile(logsFolderPath + '/' + file, 'utf-8');
const logList = JSON.parse(content);
logList.forEach((log) => {
// 4TH - NOT OK
console.log(1)
logData.push(log);
});
});
// 2ND - NOT OK
console.log(2);
} catch (error) {
console.log(error);
}
// 3RD - NOT OK, EMPTY ARRAY (deta is 100% pushing in the forEach loop)
console.log(logData);
return logData;
};
module.exports = {
getAuditLogsData
};
Is there something wrong with async/await promises?
UPDATE
I've updated the code to for-of loop, but it still didn't work:
try {
const files = await readDirectory(logsFolderPath);
// 1ST - OK
console.log(files);
for (const file of files) {
const content = await readFile(logsFolderPath + '/' + file, 'utf-8');
const logList = JSON.parse(content);
logList.forEach((log) => {
// 4TH - NOT OK
console.log(1);
// console.log(log);
logData.push(log);
// console.log(logData);
});
}
// 2ND - NOT OK
console.log(2);
} catch (error) {
console.log(error);
}
Shall I change the fs
methods to a synchronous one?
Can you tell me where is the mistake in this code?