V
V
valis2017-06-20 09:18:36
Node.js
valis, 2017-06-20 09:18:36

Why wrap a named function in an anonymous one in JS?

Now I am reading a wonderful book about the stack mean and came across a trick that is strange for me:

function addReview(req, res) {
  getLocationInfo(req,res,function(req,res,responseData){
    renderReviewForm(req,res,responseData);
  });
}

That is, I call the getLocationInfo function and, as one of the arguments, I pass an anonymous callback function that calls the named renderReviewForm
To be honest, I have not yet understood the meaning of this action, is it possible to pass the named function right away:
function addReview(req, res) {
  getLocationInfo(req,res,renderReviewForm);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2017-06-20
@vshvydky

most likely your getLocationInfo function at the time of its execution does some calculations you need, which are then called through a callback call, the only thing that is not clear to me is why they need to pass req res and so they will be in a closure.
For example, let's say your function should work with the location info that is in res.body.locateionData and when the data is received, execute the callback function. where you can process this data. I'll write an example the same way, passing req res so you can get the gist of what's going on.

function getLocationInfo(req, res, cb) {
    var responseData = "";
    if(res.body.locateionData) responseData = res.body.locateionData;
    cb(req,res,responseData);
}

When you call a function
getLocationInfo(req,res,function(req,res,responseData){
    renderReviewForm(req,res,responseData);
  });

You are essentially doing a function declaration cb
var cb = function(req,res,responseData){
    renderReviewForm(req,res,responseData);
  };

Now your function has all the arguments and is ready to be executed.
This example is of course abstract, you need to understand that the callback is called more often in asynchronous situations where a request or event subscription is embedded and it is required to wait for execution. But he explains the point. good luck.

V
vintage, 2017-06-20
@vintage

Apparently not such a book and wonderful :-) There is no point in this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question