I am still trying to understand synchronicity in JS. The following script can log different values. How can I ensure it to log a stable value? Appreciate any helps.
// variable "all" is the array which holds the file path as string
all.forEach(async(f) => {
promise = new Promise((resolve, reject) => {
fs.readFile(f, 'utf8', function (err, content) {
if (!err) {
scenario += (content.match(/Scenario(\s?)\(\'/g) || []).length;
uc += (content.match(/\/\/(\s?)UC-(.)+/g) || []).length;
resolve([scenario, uc]);
} else {
reject('Error!');
}
});
});
await promise;
});
promise.then(([scenario, uc]) => {
console.log('Total Scenarios: ' + scenario);
console.log('Total UCs: ' + uc);
});
Edit: Following code works correctly for me
As taking reference of @Yftach and @Manjeet Thakur responses.
This code works correctly for me;
let promises = all.map(f => {
return new Promise((resolve, reject) => {
fs.readFile(f, 'utf8', function (err, content) {
if (!err) {
scenario += (content.match(/Scenario(\s?)\(\'/g) || []).length;
uc += (content.match(/\/\/(\s?)UC-(.)+/g) || []).length;
resolve([scenario, uc]);
} else {
reject('Error!');
}
});
});
});
Promise.all(promises).then((result) => {
let max = result.reduce((acc, curr) => {
return [Math.max(acc[0],curr[0]), Math.max(acc[1],curr[1])];
});
console.log('Total Scenarios: ' + max[0]);
console.log('Total UCs: ' + max[1]);
});
});