When to use next() and return next() in Node.js

前端 未结 5 2021
执念已碎
执念已碎 2020-11-30 17:07

Scenario: Consider the following is the part of code from a node web app.

app.get(\'/users/:id?\', function(req, res, next){
    var id = re         


        
5条回答
  •  醉话见心
    2020-11-30 17:47

    As @Laurent Perrin's answer:

    If you don't do it, you risk triggering the callback a second time later, which usually has devastating results

    I give an example here if you write middleware like this:

    app.use((req, res, next) => {
      console.log('This is a middleware')
      next()
      console.log('This is first-half middleware')
    })
    
    app.use((req, res, next) => {
      console.log('This is second middleware')
      next()
    })
    
    app.use((req, res, next) => {
      console.log('This is third middleware')
      next()
    })
    

    You will find out that the output in console is:

    This is a middleware
    This is second middleware
    This is third middleware
    This is first-half middleware
    

    That is, it runs the code below next() after all middleware function finished.

    However, if you use return next(), it will jump out the callback immediately and the code below return next() in the callback will be unreachable.

提交回复
热议问题