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

前端 未结 5 2020
执念已碎
执念已碎 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:55

    Some people always write return next() is to ensure that the execution stops after triggering the callback.

    If you don't do it, you risk triggering the callback a second time later, which usually has devastating results. Your code is fine as it is, but I would rewrite it as:

    app.get('/users/:id?', function(req, res, next){
        var id = req.params.id;
    
        if(!id)
            return next();
    
        // do something
    });
    

    It saves me an indentation level, and when I read the code again later, I'm sure there is no way next is called twice.

提交回复
热议问题