Transfering an anonymous function to a named function

Transfering an anonymous function to a named function
0

#1

This express route handler works with or without the function being named:

app.post('/signup', function saveNewUserAndRedirect(req, res) {
  console.log(req.body)
});

But then when I refactor to this it breaks:

function saveNewUserAndRedirect (request, response) {
  console.log(request.body);
};

app.post('/signup', saveNewUserAndRedirect(req, res));

looks like req and res are not passing in correctly. What is the issue with that code?


#2

Since the function is defined, just reference the function.

function saveNewUserAndRedirect (request, response) {
  console.log(request.body);
};

app.post('/signup', saveNewUserAndRedirect);

With your code, you are attempting to call the function with arguments req and res which are undefined. You do not want to call the function, you just want to reference it, so it gets called by the post method.


#3

Thank you. To clarify what you said, I take it that the app.post() method passes req and res values into a function declaration in the 2nd argument.

But when I tried to call the function myself it broke because req and res weren’t defined.

but when I declare the function and reference it, then it works again because the 2nd argument of app.post() receives req and res values based on parameter order.

Is that accurate? I sort of understand function referencing so I just wanted to confirm I’m thinking about this correctly.


#4

loosely speaking, when you run the route Js will add (req, res) for you at the end

so saveNewUserAndRedirect is just a ‘callback’ that returns the function itself the same way you wrote it

console.log(newUser) without () and youre just going to get [Function]

how you wrote it:

(function newUser(){ return 1+1 })(req, res)

how it should be:

function newUser(){ return 1+1 }