接下来是什么();在这段代码中? [英] What is next(); in this code?

查看:42
本文介绍了接下来是什么();在这段代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我不理解的Express应用程序中(针对Node.js),有一行代码使用 next(); .我想知道您是否可以澄清.

There's a line of code using next(); in this Express app (for Nodejs) that I don't understand. I wonder if you could clarify.

在index.js中,快速应用程序调用函数isLoggedInMiddleware.它没有传递任何参数

In index.js, the express app calls a function isLoggedInMiddleware. It doesn't pass any parameters

 app.use(sessionHandler.isLoggedInMiddleware);

这是该功能.调用它时,它没有传递任何参数,但设置为接受三个参数,其中 next 是最后一个,称为getUsername的返回值.

Here is that function. When it was called, it wasn't passed any parameters, but it's set up to accept three, with next being the last, which is called as the return value of getUsername.

this.isLoggedInMiddleware = function(req, res, next) {
    var session_id = req.cookies.session;
    sessions.getUsername(session_id, function(err, username) {
        "use strict";

        if (!err && username) {
            req.username = username;
        }
        return next();
    });
}

这是getUserName其中next();作为callbak的一部分传递给.你能解释下next();被使用了吗?在这种情况下是什么?在做什么?

This is getUserName which next(); gets passed to as part of the callbak. Can you explain how next(); was being used? what is it in this context? what is it doing?

this.getUsername = function(session_id, callback) {
        "use strict";

        if (!session_id) {
            callback(Error("Session not set"), null);
            return;
        }

        sessions.findOne({ '_id' : session_id }, function(err, session) {
            "use strict";

            if (err) return callback(err, null);

            if (!session) {
                callback(new Error("Session: " + session + " does not exist"), null);
                return;
            }

            callback(null, session.username);
        });
    }

推荐答案

它将控件传递回Express应用程序,以调用链中的下一个中间件/请求处理程序.

It passes the control back to the express app to invoke next middleware/request handler in chain.

这里:

app.use(sessionHandler.isLoggedInMiddleware);

您告诉Express使用 isLoggedInMiddleware 作为中间件.

you told express to use isLoggedInMiddleware as middleware.

每个中间件都会收到:

  • 请求-丰富和/或查询
  • 响应-如果他们想写点东西(例如错误)
  • 允许Express继续处理请求的回调.

该中间件在被express调用时,会用用户数据丰富请求对象,然后将控件返回给express,然后继续到下一个中​​间件或处理程序.

That middleware, when called by express, enriches the request object with user data and then returns the control back to express, which then continues to next middleware or to handler.

这篇关于接下来是什么();在这段代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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