javascript node.js 回调中“完成”和“下一步”之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26164837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:36:21  来源:igfitidea点击:

difference between 'done' and 'next' in node.js callbacks

javascriptnode.jsexpresspassport.js

提问by Tara Roys

in the passport [configure authentication] documentation, it has a rather scary-looking function that uses the mysterious function "done.'

在passport [configure authentication] 文档中,它有一个看起来很吓人的功能,它使用了神秘的功能“done”。

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
   }
));

Now, in the express documentationthere are quite a few methods that pass something called next.

现在,在express 文档中,有很多方法可以传递称为 next 的东西。

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Is this the difference between the two frameworks, express and passport? Or are they doing two separate things?

这是快递和护照这两个框架的区别吗?还是他们在做两件不同的事情?

回答by mithunsatheesh

Is this the difference between the two frameworks, express and passport?

这是快递和护照这两个框架的区别吗?

No they are different in the purpose for which they are used for. Express is used as a application framework on node.js where as passport just handles the authentication part of a web application.

不,它们的用途不同。Express 用作 node.js 上的应用程序框架,其中 Passport 仅处理 Web 应用程序的身份验证部分。

about next()

关于下一个()

next() is part of connect which inturn is an express dependency. The purpose of calling next() is to trigger the next middle ware in express stack.

next() 是 connect 的一部分,而后者又是一个明确的依赖项。调用next()的目的是触发express stack中的下一个中间件。

To understand the next()concept in an easier way, you could look at a sample app built on express here.

next()以更简单的方式理解该概念,您可以在此处查看基于express构建的示例应用程序。

as you can see in the line pointed the application uses a route level middleware to check whether the user is logged in or not.

正如您在指向的行中看到的,应用程序使用路由级中间件来检查用户是否已登录。

app.get('/account', ensureAuthenticated, function(req, res){

Here ensureAuthenticated is the middleware which is defined at bottom like

这里 ensureAuthenticated 是在底部定义的中间件,如

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

as you can see if the user is authenticated the function invokes next()and passes control to the next layer in route handler written above, else it redirects to another route even without invoking the next()

如您所见,如果用户已通过身份验证,该函数调用next()并将控制传递到上面编写的路由处理程序中的下一层,否则即使不调用next()

about done()

关于完成()

done() on the other hand is used to trigger the return url handlers that we write for passport authentication. To understand more on how done works you could look at the code samples at passport hereand check the section titled Custom Callback

done() 另一方面用于触发我们为护照身份验证编写的返回 url 处理程序。要了解有关 done 工作原理的更多信息,您可以在此处查看护照中的代码示例并查看标题为自定义回调的部分

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

Here the second parameter to passport.authenticateis the definition of done()that you are going to call from the passport strategy.

这里的第二个参数 topassport.authenticatedone()您将从通行证策略调用的定义。

note

笔记

Here going through the sample codes in the two links I provided above have helped alot in understanding its behavior than the docs. I would suggest you to do the same.

在这里通过我上面提供的两个链接中的示例代码比文档更有助于理解它的行为。我建议你也这样做。

回答by Robert Levy

passport's done() wants you to pass in an error (or null) for the first param and a user object as the 2nd param.

护照的 done() 要求您为第一个参数传递错误(或空值),并将用户对象作为第二个参数传递。

express's next() wants an error in the first param or to be called with no parameter at all if there wasn't an error. you could also pass the name of a route to redirect control to in the first parameter but this isn't very common

express 的 next() 想要在第一个参数中出现错误,或者如果没有错误则根本不带参数地调用。您还可以在第一个参数中传递路由的名称以将控制重定向到,但这并不常见

回答by Jason

Let's back up because I think you may have some confusion.

让我们备份,因为我认为你可能有一些困惑。

Express is a web application framework. It's responsible for directing users to resources, in a very broad sense.

Express 是一个 Web 应用程序框架。从广义上讲,它负责将用户引导到资源。

Passport is a authentication framework. It's responsible for making sure that users are allowed to access said resources.

Passport 是一个身份验证框架。它负责确保允许用户访问所述资源。

In both frameworks there is a idea of middleware. Middleware is basically generalized control flow. For example, in some Express framework you could say:

在这两个框架中都有中间件的概念。中间件基本上是广义的控制流。例如,在某些 Express 框架中,您可以说:

  1. Make sure parameter x is valid when requesting route /user/:x

    • if valid, then next() --> which means go to next middleware function()
  2. Make sure the user has a session, etc

  3. And when all middleware has been executed, then we execute the application

  1. 请求路由时确保参数 x 有效 /user/:x

    • 如果有效,则 next() --> 表示转到下一个中​​间件 function()
  2. 确保用户有一个会话等

  3. 当所有中间件都执行完毕,然后我们执行应用程序

For example,

例如,

router.get('/', function(req, res) { // when the '/' route is requested
    res.render('index', { title: 'Express' }); // send index.html
});

In Passport, they also use the idea of middleware, however, instead of next(), they use done() and it's a little more complex. See this page for more info
http://toon.io/understanding-passportjs-authentication-flow/

在 Passport 中,他们也使用了中间件的思想,但是,他们使用的是 done() 而不是 next() ,它有点复杂。有关更多信息,请参阅此页面
http://toon.io/understanding-passportjs-authentication-flow/