什么是 Passport Strategy Configure "use" 函数中的 "done" 回调函数

What is "done" callback function in Passport Strategy Configure "use" function

我是 node.js 和 express.js 菜鸟。这个问题可能看起来很愚蠢,但我真的很困惑。

我正在尝试配置 Local Strategry authentication by using passport。如官方文档所示,我们可以通过以下代码来理解这个Local Strategy,

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); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

我的困惑是关于 done 回调函数。当官方文档显示此本地策略在路由处理程序中用作中间件时,无需为此 done 回调传递函数参数。

app.post('/login', 
  passport.authenticate('local'),
  function(req, res) {
    res.redirect('/');
  });

那么,如果我们不提供函数参数,这个done回调函数不就是null吗?如果不是,那个done回调函数是什么,这个done回调函数会发生什么过程?

done 是一种方法 called internally by the strategy implementation.

然后,如您所见,它会将您导航到 success / error / fail 方法之一(同样,通过实现。there are more options) . 这些选项中的每一个都可以 callsnext,其中您的代码段代码如下:

function(req, res) {
  res.redirect('/');
});

当调用 success 时,it can attach the user to the request or do other things, depending on your needs (it looks for the options you pass to passport.authenticate). If you want to determine when next will be called, you should use custom callback 给你更多的灵活性。

我强烈建议您阅读源代码。