nodejsinaction icon indicating copy to clipboard operation
nodejsinaction copied to clipboard

Is IIFE in word count example in chapter 2 necessary?

Open nur557 opened this issue 4 years ago • 0 comments

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)
})

nur557 avatar Dec 03 '21 14:12 nur557