何时在Node.js中使用next()并返回next() [英] When to use next() and return next() in Node.js

查看:108
本文介绍了何时在Node.js中使用next()并返回next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案:请考虑以下内容来自节点网络应用程序的代码。

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

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

问题:我正在检查哪一个只是 next() return next()。对于上述代码示例,这两个代码的工作方式与执行部分没有任何差异。

Issue: I am checking which one to go for just next() or return next(). For the above code sample both the codes works exactly the same way did not show any difference in execution part.

问题:有人可以使用 next()什么时候使用 return next()和一些重要的区别?

Question: Can some one put light of when to use next() and when to use return next() and some important difference?

推荐答案

有些人总是写 return next()是为了确保触发回调后执行停止。

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
});

它为我提供了缩进级别,当我稍后再次阅读代码时,我确信没有办法 next 被调用两次。

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.

这篇关于何时在Node.js中使用next()并返回next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆