JS承诺。一些节点 js 和护照 js。如何从 promise {{}} 中获取内部结构? req.user

JS promise. Some node js and passport js. How can I get an internal structure from promise { {} }? req.user

我无法从 req.user 中获取项目,当我尝试查看 req.user 中的内容时,它显示:

Promise {
  {
    login: 'login',
    password: 'b$sivL/8KvPYzlN/b24nWNOOa7pd02WX',
    id: 12,
    role: 'user'
  }
}

原来我可以输出Promise { {} },但我只需要内部结构,如何获取进一步处理(仅以角色为例)?

req.user 设置在那里(根据指南)

const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')

function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, password, done) => {
    const user = await getUserByEmail(email)
    if (user == null) {
      return done(null, false, { message: 'No user with that email' })
    }

    try {
      if (await bcrypt.compare(password, user.password)) {
        return done(null, user)
      } else {
        return done(null, false, { message: 'Password incorrect' })
      }
    } catch (e) {
      return done(e)
    }
  }

  passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
  passport.serializeUser((user, done) => done(null, user.id))
  passport.deserializeUser((id, done) => {
    return done(null, getUserById(id))
  })
}

module.exports = initialize

编辑:在看到您的策略后,我可以看出问题出在 deserializeUser 中。看起来像getUserById return的承诺,所以你需要先得到结果:

  passport.deserializeUser(async (id, done) => {
    const user = await getUserById(id);
    return done(null, user);
  })

以前的答案以防对其他人有帮助:

您的问题很可能出在您的登录策略上,而不是您想要消费的地方 req.user

假设您使用 LocalStrategy 作为护照,您 return 在回调中最终解析的用户记录如下:

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Example service returning a promise
    UserService.loginWithPassword({ username, password }.then((user) => {
      if (!user) return done(null, false);
      return done(null, user);
    }).catch(error => {
      return done(err);
    });
  }
));

如果您不解决 awaitthen 的承诺,您最终会得到 req.user 的承诺,就像您在问题中的承诺:

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Example service returning a promise
    const user = UserService.loginWithPassword({ username, password });
    // user will always be a promise here
    if (!user) return done(null, false);
    return done(null, user);
    // now `req.user` is the promise, instead of the user object
  }
));