gags gags - 2 months ago 10
Javascript Question

Why return anonymous function from a javascript function

Here the function returns an anonymous function:

function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if(entity) {
return res.status(statusCode).json(entity);
}
return null;
};
}



  1. Why is it that we are returning an anonymous function here that returns a value? What advantages do we have and when to try something like this?

  2. How and what is this anonymous function's argument
    entity
    is populated with? We passed res to
    respondWithResult
    and what exactly happens next that we got
    entity
    for an argument in the anonymous function? What value does this argument get populated with?

  3. In case it gets populated with
    res
    only, what's wrong with directly doing this instead:

    if(res){
    //bla bla
    }
    return null



Edit: The function is called like this:

return Outlet.find().exec()
.then(respondWithResult(res))
.catch(handleError(res));


Now,
res
is what we pass to
respondWithResult
. Is that what the anonymous functions gets in the argument? If yes, what is the advantage?Why not use res directly?

Answer

Why is it that we are returning an anonymous function here that returns a value? What advantages do we have and when to try something like this?

This is generally done because it has access to the scope of the function it was declared within. i.e. the local variables statusCode and res. Without more context it isn't immediately obvious why that is useful here.

How and what is this anonymous function's argument entity is populated with?

It's a function argument. It gets populated with whatever gets passed to it when it is called (which isn't in the code you shared).

As you pointed out, the function is returned (not immediately executed). Some other code will call it later.

Now, res is what we pass to respondWithResult. Is that what the anonymous functions gets in the argument? If

No. The returned function is passed to then. When the promise resolves, the result is passed to it.