Wozer
Wozer

Reputation: 45

Route running before Middleware promise completes

I am having an issue with my code and some middleware. I have a function that gets a list of nav items for a user and I store them in res.locals. However for some reason I am now having an issue that was not there a few days ago. My app.get('/' function runs before the middleware promise completes.

Here is my route code:

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

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

and my middleware:

// 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");
};

Any ideas why this might not be working?

Upvotes: 0

Views: 123

Answers (1)

IAmDranged
IAmDranged

Reputation: 3020

As per my comment above, this should work better - ie call the next middleware/route in line only when the navPromise has resolved.

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");
};

Upvotes: 2

Related Questions