I'm very confused about this program. I bought a book called "Node JS, MongoDB, and AngularJS Web Development" by Brad Dayley. I found a program to demonstrate something called closure, and it shows this program as an example. This is only the first part of the program.
function logCar(logMsg, callback){
process.nextTick(function(){
callback(logMsg);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti"];
for(var idx in cars){
var message = "Saw a " + cars[idx];
logCar(message, function(){
console.log("Normal Callback: " + message);
})
}
I've been trying to figure out how this program functions for an entire hour, but I can't figure out what the function of callback(logMsg).
I know this is probably a very basic question, but I just can't wrap my head around it.
callback is any function that you pass to logCar(). When logCar completes doing whatever it is supposed to do, then it will call the callback function. Inside your for loop, you call logCar() like this..
logCar(message, function(){
console.log("Normal Callback: " + message);
})
Here, function() {..} is the callback function and it will be called once logCar is done executing. In this case, the callback function you've provided will console.log
the message you've passed as the first parameter. You could have passed another function that would perform something different as a callback too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With