Search code examples
javascriptecmascript-6arrow-functions

Avoid Passing arrow function params to another function


I'm using express and am using an arrow function to handle my req,res params. I'm delegating this req,res to another helper function though.

I.e.

app.get("/Model/:id", (req, res) => { Handler.model(req, res) });    

My question is if I can avoid that redundancy and just do something like

app.get("/Model/:id", Handler.model(req, res));

Solution

  • You can probably do a η-reduction:

    app.get("/Model/:id", Handler.model);
    

    However you might have to bind it:

    app.get("/Model/:id", Handler.model.bind(Handler));
    

    Notice that unlike your original arrow function, this does pass an arbitrary amount of arguments to the model method, not exactly two, and it does return the return value of the model method instead of nothing (undefined). It depends on app.get and Handler.model whether they can deal with those minor differences.