1

Let's say we are using express. Why are we using callbacks like this:

var port = process.env.PORT || 8080;
app.listen(port, function(){
    console.log('Listenning: ' + port);
});

instead of this:

var port = process.env.PORT || 8080;
var onBegin = function() {
    console.log('Listenning: ' + port);
}
app.listen(port, onBegin);

Is this a must? Or the second one can cause problems? I see that lots of people use inline callbacks but why don't they simply define all callbacks in another block or a file? If this is a must, where can i find all best practices? For example i have found the following link, but can you recommend something else maybe? Like musts, basics and etc.

The link i have found: https://www.codementor.io/mattgoldspink/nodejs-best-practices-du1086jja

EDIT:

Here is the another callback function as a variable i am using with parameters:

var onGET = function(req, res) {
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log('User connected: ' + ip);
    res.send('OK: ' + req.query.id);
}
app.get('*', onGET);
blacksun
  • 733
  • 7
  • 24

3 Answers3

1

Anonymous callbacks are commonly shown in tutorials and guides because it's easier to understand for beginners. While developing an actual application, it doesn't work.

Here's an example of an actual route:

app.get('/user/', User.authenticate, User.getData);

Notice, how easy it is to understand this way. The other way works only in guides and tutorials, for actual application, use named middlewares.


EDIT: In the end, it's how you understand best. For functions which are called one time like the app.listen callback, you may skip naming them. It looks more readable that way.

tbking
  • 8,796
  • 2
  • 20
  • 33
0

There is no difference, functionally. You might want to use anonymous functions, because they can be easier to read, thus making the code easier to maintain in the future.

It is fine to define your callbacks in another block or a file, but keep an eye on scope.

Adam Patterson
  • 958
  • 7
  • 13
0

Leveraging on the responses above,

You can have them separated it will still work.

In a more juicy way if you are running on latest version on NodeJS you can write the above code as below:

var port = process.env.PORT || 8080;
    app.listen(port, => console.log('Listenning: ' + port);
);

var onGET = (req, res) => {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log('User connected: ' + ip);
res.send('OK: ' + req.query.id);
}
app.get('*', onGET);

If there is need for more clarity, drop the questions below.

Hope this helps..

ajafik
  • 147
  • 1
  • 5