Callback () Node Js

I am very confused by this program. I bought a book called "Node JS, MongoDB, and AngularJS Web Development" by Brad Daily. I found a program to demonstrate something called closure, and 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 tried to figure out how this program functions for an entire hour, but I cannot figure out what the callback function (logMsg) is.

I know this is probably a very simple question, but I just can't wrap my head around it.

+5
source share
2 answers

callback is any function that you pass logCar (). When logCar completes what it should do, it calls the callback function. Inside the for loop, you call logCar () as follows.

 logCar(message, function(){ console.log("Normal Callback: " + message); }) 

Here the function () {..} is a callback function, and it will be called after logCar is executed. In this case, the callback function you provided will be the console.log message that you passed as the first parameter. You could pass another function that will perform something else as a callback.

+2
source

I find it easier to wrap my head following the execution path in more detail, especially the path that logMsg accepts. A good debugger is great for this.

Nothing happens until in a loop where a variable called message is defined. At the beginning, it will be the Ferrari Saw.

There is also an anonymous function next to the โ€œmessageโ€, which, unfortunately, is difficult to separate and define. Since it goes beyond its scope for a variable called "message" that falls inside this loop, we could not do on line 6:

 var someFunction = function(){ console.log("Normal Callback: " + message); } 

... because what kind of "message"? Nothing outside this for-loop has direct access to the โ€œmessageโ€ (other than closing, but don't worry about that yet). Please note that this function will not be executed yet. It has just been created at this moment.

So the next one is done by LogCar("Saw a Ferrari", someFunction...) . Where is LogCar? Oh top. Let it jump there, but for simplicity let it skip process.nextTick. Essentially someFunction("Saw a Ferrari") happens here. Where is some function? Oh, this anonymous function that has not yet been executed. It's time to execute it. Thus, the process jumps back to see what is inside it and execute it, which is console.log("Saw a Ferrari");

This is done, and the process is repeated for "Saw a Porsche".

+2
source

All Articles