javascript node.js next() [英] javascript node.js next()

查看:1019
本文介绍了javascript node.js next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js中看到很多使用 next

I see a lot of use next in node.js.

这是什么,它在哪里来自?它有什么作用?我可以在客户端使用吗?

What is it, where does it come from? What does it do? Can I use it client side?

很抱歉,例如这里使用它:
http://dailyjs.com/2010/12/06/node-tutorial-5/

Sorry it's used for example here: http://dailyjs.com/2010/12/06/node-tutorial-5/

看对于loadUser函数。

look for the loadUser function.

推荐答案

这似乎是Node.js控制流代码中的变量命名约定,其中有一个引用下一个要执行的函数被赋予一个回调函数,以便在它完成时启动它。

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

例如,请参阅此处的代码示例:

See, for example, the code samples here:

  • http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets/

让我们来看看你发布的例子:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

loadUser 函数需要一个函数第三个参数,绑定到名称 next 。这是一个正常的函数参数。它包含对下一个要执行的操作的引用,并在完成 loadUser 后调用(除非找不到用户)。

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

在这个例子中,名称 next 没有什么特别之处;我们可以把它命名为任何东西。

There's nothing special about the name next in this example; we could have named it anything.

这篇关于javascript node.js next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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