Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback() Node Js

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.

like image 963
studentTrader24 Avatar asked Jun 20 '15 03:06

studentTrader24


1 Answers

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.

like image 95
Bidhan Avatar answered Oct 15 '22 23:10

Bidhan