I know this has been asked a million times, but I'm really trying to break down async Javascript functions and callbacks and its just not clicking. I'm looking at Max Ogden's Art of Node example which is this:
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)
Breaking this down, I understand that when addOne is invoked, it first kicks off fs.ReadFile which may take some time to complete.
What I don't get is, won't the code continue to callback() and execute logMyNumber (before myNumber has been added to) anyhow? What's stopping callback() from running before it should, which is the whole point? Or does callback() not happen until doneReading has happened? Are we supposed to assume that doneReading will be invoked when fs.readFile is "done"?
Thank you all for your patience in helping me with this very common question:)