护照反序列化的新方式会是什么样的?

huangapple go评论70阅读模式
英文:

What would the new way of passport deserialization look like?

问题

我正在按照一个简单的MVC教程https://blog.logrocket.com/building-structuring-node-js-mvc-application/来构建一个登录认证系统。

直到几天前,我的代码中还有一个工作正常的序列化和反序列化部分

passport.serializeUser((user, done) => {
    done(null, user.id);
  });
  
  passport.deserializeUser(async (id, done) => {
    
    User.findById(id, (error, user) => {
      done(error, user);
    });

  });

最近运行代码时,我开始收到错误消息Model.findById()不再接受回调。现在我明白新的方式是使用async和await来编写代码。然而,我找不到一个在线示例,指导我如何编写代码。请问我可以在这里得到帮助吗?

英文:

In am following a simple MVC tutorial https://blog.logrocket.com/building-structuring-node-js-mvc-application/ to build a login authentication system.

Till a few days back, I had a working serialize and deserialize section in my code

passport.serializeUser((user, done) => {
    done(null, user.id);
  });
  
  passport.deserializeUser(async (id, done) => {
    
    User.findById(id, (error, user) => {
      done(error, user);
    });

  });

Recently running the code, I started getting the error Model.findById() no longer accepts a callback
Now I understand that the new way would be using write async and await. However, I couldn't find a sample online that guides me towards how to come about writing the code. Could I please be helped here?

答案1

得分: 3

你的问题更多涉及Mongoose而不是Passport问题,Mongoose现在使用承诺而不是回调。

要将你的代码转换,你可以使用async/await来处理承诺,但仍然需要调用passport.deserializeUser提供的回调函数:

passport.deserializeUser(async (id, done) => {
  try {
    return done(null, await User.findById(id));
  } catch(error) {
    return done(error);
  } 
});
英文:

Your question isn't so much a Passport question, but a Mongoose question, which now uses promises instead of callbacks.

To convert your code, you can handle the promise using async/await, but you still need to call the callback provided by passport.deserializeUser:

passport.deserializeUser(async (id, done) => {
  try {
    return done(null, await User.findById(id));
  } catch(error) {
    return done(error);
  } 
});

huangapple
  • 本文由 发表于 2023年4月13日 15:38:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定