nodejsinaction
nodejsinaction copied to clipboard
Is IIFE in word count example in chapter 2 necessary?
I'm referring to this part of the code:
files.forEach((file) => {
const task = ((file) => {
return () => {
fs.readFile(file, (err, text) => {
if (err) throw err
countWordsInText(text)
checkIfComplete()
})
}
})(`${filesDir}/${file}`)
tasks.push(task)
})
Because a new binding file is created for each callback we’ve already ensured that fs.readFile will be working with the right file? Or am I misunderstanding something? Couldn't this be written as:
files.forEach((file) => {
const task = () => {
fs.readFile(`${filesDir}/${file}`, (err, text) => {
if (err) throw err
countWordsInText(text)
checkIfComplete()
})
}
tasks.push(task)
})