Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is next() in NodeJs?

I am new to NodeJs coming from Java background, I'm trying to understand the use of the convention next() call.

I've gone through the following posts -
1. javascript node.js next()
2. https://www.naeemrana.com/node-js/express-js-middleware-what-is-next/
3. When to use next() and return next() in Node.js

What I could make of them is next() is similar to a callback or maybe a reference of the next function to be executed after the current function's execution,
Also understood it's recommended to use return next(); instead of next(); to avoid the function to be re-executed.

Following is a sample code from one the links -

app.get('/users/:id', function(req, res) {
    var user_id = req.params.id;

    if(user_id) {
      // do something
    } else {
      next(); // here comes middleware.
    }
});

What I don't understand here is the function being executed does not have the 3rd argument,
but it does invoke the next() function, what is the idea here?
Is the use of this convention only to be used on routes logic?
Is next() a callback? is it a reference to the next function to be executed? or something else?

like image 309
Ani Avatar asked Nov 04 '18 04:11

Ani


1 Answers

Node.Js doesn't know next. It's a pattern used by the express framework.

As express has a concept of middlewares that can be called in each and every request coming into it.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

var app = express()

app.use(function (req, res, next) {
  if(condition_to_return_from_here){
    res.end(req.params.id)
  }else{
  console.log('Time:', Date.now())
  next()
 }
})

More on expressjs and middleware - https://expressjs.com/en/guide/using-middleware.html

like image 153
front_end_dev Avatar answered Oct 08 '22 01:10

front_end_dev