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

查看:34
本文介绍了何时在 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(); //or return next();
    }
});

问题:我正在检查哪一个只使用 next()return next().上面的示例代码对 & 的工作方式完全相同.在执行上没有表现出任何差异.

Issue: I am checking which one to go with just next() or return next(). Above sample code works exactly the same for both & did not show any difference in execution.

问题:有人可以解释一下,何时使用 next() 以及何时使用 return next() 和一些重要区别?

Question: Can some one put light on this, 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天全站免登陆