max-mapper / art-of-node

:snowflake: a short introduction to node.js
https://github.com/maxogden/art-of-node#the-art-of-node
Other
9.81k stars 854 forks source link

Callbacks pseudocode missing passed arguments #61

Closed wonder95 closed 8 years ago

wonder95 commented 9 years ago

In the [Callbacks]() section, the code example it gives seems to be missing some passed arguments. In particular, this code:

var fs = require('fs')
var myNumber = undefined

function addOne(callback) {
  fs.readFile('number.txt', function doneReading(err, fileContents) {
    myNumber = parseInt(fileContents)
    myNumber++
    callback()
  })
}

function logMyNumber() {
  console.log(myNumber)
}

addOne(logMyNumber)

doesn't pass anything to logMyNumber(). I was using this exact code for the async i/o exercise in the learnyounode tutorial, and I was getting a 0 returned. When I changed the code to this:

var fs = require('fs')
var myNumber = undefined

function addOne(callback) {
  fs.readFile('number.txt', function doneReading(err, fileContents) {
    myNumber = parseInt(fileContents)
    myNumber++
    callback(myNumber)
  })
}

function logMyNumber(myNumber) {
  console.log(myNumber)
}

addOne(logMyNumber)

it worked as expected. I'm not sure if I'm missing some JS idiosyncrasy, but this is what worked for me.

zeke commented 8 years ago

Thanks for the report, @wonder95. I just tried the original code myself, and it seems to work. Something must have been funny with your configuration.

Happy hacking!