Search code examples
node.jsfunctioncallbackcommon-library

How to pass function as callback function in node


I have created following function in common library created in node to create route.

public registerRoute(verb:string,route:string,cb:(req:any,resp:any)=>any):any
    {

        this.app.get(route,cb);
}

I am importing this library and calling this function in my another node project like following.

logger.registerRoute("GET","/route/testapi",testapi(req,resp))

function testapi(req:any , resp:any):any
{
    resp.send("Function called");
}

But I am getting error as cannot find req and resp logger.registerRoute("GET","/route/testapi",testapi(req,resp))

How can I pass this function as callback function to this common library function??


Solution

  • When you pass the callback into: logger.registerRoute("GET","/route/testapi",testapi(req,resp))

    you actually want to just pass the definition (method without parenthesis and args):

    logger.registerRoute("GET","/route/testapi",testapi)

    otherwise it will run when you pass it not when it is supposed to as a callback.