apdm apdm - 2 months ago 6
Node.js Question

If I replace an object that is equal to a function with the function itself, code no longer works?

I'm unfamiliar with this syntax. I have a function set up to handle socket requests like so:

//Predefined function is stored in the sensors object
var sensors = { pre-defined-function: function(req, res, next){
console.log('Test');
next();
}

exports.make_socket_controller = function (sockets) {
return function (req, res, next) {

//Predefined function is called
sensors['pre-defined-function']

(req, res, function() {
//another function
}


If I replace the
sensors[pre-defined-function]
with the actual function itself, I get a syntax error

function(req, res, next){
console.log('Test');
next();
}
(req, res, function() {
//another function
}


Also, what does it mean when the end of one function somehow rolls into another? I've never seen the end of one function be immediately followed by parentheses.

Answer

You need to add parentheses around the function literal when you want to immediately invoke it:

(function(req, res, next){
  console.log('Test');
  next();
})(req, res, function() {
  // another function
});
Comments