1

I'm very new to Node.js and I'm just trying to make sense of how the parameters work in the callback methods of the code.

I can only understand the first one, function(req,res), because I've used that in Java when working server-side, but I don't really understand how it automatically calls the memcached function or how that kicks off the rest, etc. If somebody could explain to me how this works I'd really appreciate it. Thank you

server.on('request', function(req, res) {
  //get session information from memcached 
   memcached.getSession(req, function(session) {
    //get information from db 
    db.get(session.user, function(userData) {
      //some other web service call 
      ws.get(req, function(wsData) {
         //render page
         page = pageRender(req, session, userData, wsData);
         //output the response
         res.write(page);
         });
      });
    });
});
6
  • 1
    It doesn't automatically call anything, the call to memcached is hardcoded and right there, and it's like any other function call, it passes the request argument on, and has a callback function that is executed once whatever it is it does is finished ? Commented Dec 22, 2013 at 20:44
  • Ok, I understand it a bit better I think.. but where is getSession's call back getting the session variable from? Commented Dec 22, 2013 at 20:48
  • 1
    It's getting it internally and returning it in the callback. If you want to figure out exactly where it's coming from, look at the source code for the memcached middleware. Commented Dec 22, 2013 at 20:50
  • It was just example code, so it wasn't complete. But you're saying for this to work, there is a variable somewhere in between that's called session? That makes more sense to me. Commented Dec 22, 2013 at 20:52
  • @WendellBlatt callback receives session as argument, I assume memcached use request object to initiate session, for example checks cookie for session ID. Commented Dec 22, 2013 at 20:53

1 Answer 1

1

It could roughly be compared to passing the anonymous class in Java. For example to sort a collection in Java you pass a comparator class which has a method for comparing two objects. Later, when sorting algorithms needs to compare the objects it calls the function in provided class.

In javascript functions are first class objects, which means we don't need a "wrapper" class and can pass it as a parameter to another function.

In your case "memcached.getSession" will execute is't logic, find the session, and calls the anonymous function you pass in the second parameter, with the session as parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.