Transfering an anonymous function to a named function

This express route handler works with or without the function being named:'/signup', function saveNewUserAndRedirect(req, res) {

But then when I refactor to this it breaks:

function saveNewUserAndRedirect (request, response) {
};'/signup', saveNewUserAndRedirect(req, res));

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

Since the function is defined, just reference the function.

function saveNewUserAndRedirect (request, response) {
};'/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.

1 Like

Thank you. To clarify what you said, I take it that the 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 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