Transfering an anonymous function to a named function

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?

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.

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 }
1 Like