在中间件承诺完成之前路由 运行

Route running before Middleware promise completes

我的代码和一些中间件有问题。我有一个函数可以获取用户的导航项列表,并将它们存储在 res.locals 中。但是由于某种原因,我现在遇到了几天前不存在的问题。我的 app.get('/' 函数在中间件承诺完成之前运行。

这是我的路线代码:

const isAuthenticated = require("../config/middleware/isAuthenticated"); 
module.exports = function(app) {

    app.get('/', isAuthenticated, function(req, res) {
        res.locals.title = 'Welcome';
        res.render('index.ejs');
    });
}

和我的中间件:

// This is middleware for restricting routes a user is not allowed to visit if not logged in
const Utils = require('../../models/Utils/utils');
module.exports = function(req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  if (req.user) {
    res.locals.user = {first_name: req.user.first_name, last_name: req.user.last_name};
    if(!res.locals.nav) {
        let navPromise = Utils.createNavs(req.user.id);
        navPromise.then(function(navItems) {
            res.locals.nav = navItems;
        });
    }
    return next();
  }
  // If the user isn't' logged in, redirect them to the login page
  return res.redirect("/login");
};

知道为什么这可能不起作用吗?

根据我上面的评论,这应该会更好 - 即仅当 navPromise 已解决时才调用下一个 middleware/route。

module.exports = function(req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  if (req.user) {
    res.locals.user = {first_name: req.user.first_name, last_name: req.user.last_name};
    if(!res.locals.nav) {
        let navPromise = Utils.createNavs(req.user.id);
        navPromise.then(function(navItems) {
            res.locals.nav = navItems;
            next()
        });
    }
    return;
  }
  // If the user isn't' logged in, redirect them to the login page
  return res.redirect("/login");
};