Awaiting Inside forEach
A subtle async bug where forEach silently ignores awaited promises inside its callback.
Codejavascript
const fs = require('fs').promises;
async function readAll(files) {
const contents = [];
files.forEach(async (file) => {
const data = await fs.readFile(file, 'utf8');
contents.push(data);
});
return contents;
}
readAll(['a.txt', 'b.txt']).then((result) => {
console.log(result.length); // expects 2, logs 0
});Why does readAll return an empty array instead of the file contents?