Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do the parameters in a javascript callback function come from?

I understand the essence of callback functions in that the function is executed again after being passed as the parameter to another function. However, I'm confused as to where the variables inside the callback function come from as shown in the following node.js example:

router.get('/', function(req, res){
    res.render('index', {});
});

How do the variables req and res get populated? An example explaining how I can just call res.render(...) without declaring res myself would be greatly appreciated.

like image 575
Danny Liu Avatar asked Jan 06 '16 02:01

Danny Liu


2 Answers

They come from the same place they come from when a normal non callback function is invoked, at invocation time.

If you have this function,

function add (a, b) {
  return a + b
}

You're fine with knowing that a and b come from when you invoke add,

add(1,2)

and it's the same principle with callbacks, don't let your brain get all twisted just because it's getting invoked later.

At some point the function you pass to router.get is going to be invoked, and when it does, it will receive req and res.

Let's pretend the definition for router.get looks like this

router.get = function(endpoint, cb){
   //do something
   var request = {}
   var response = {}
   cb(request, response) // invocation time
}

In the case of your example, it's just up to node to pass your function request and response whenever .get is invoked.

like image 160
Tyler McGinnis Avatar answered Oct 21 '22 13:10

Tyler McGinnis


The whole point of the callback is that the invoked function calls it back.

In the case of router.get, it will insert the route (path, method, callback) in a lookup table; when a request comes in, Express will construct the response object, match the request's path and method against all the entries in the lookup table, take the callback from the matching entry and invoke callback(request, response) (passing the detected request and created response).

like image 21
Amadan Avatar answered Oct 21 '22 14:10

Amadan