3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you point me to resources that could explain me the topic in detail, please? I couldn't find examples on this
Ahhh! I got it with your update. "No. The returned function is passed to then. When the promise resolves, the result is passed to it." makes complete sense :D So awesome! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.