0

I have a sails application and I want to populate the navigation bar drop-down menu data from DB.

I am using policies to call service and populate sails.config.views.locals.HeaderData variable

But because of some async feature of sails the service is getting called only when the controller has sent the response and not when the request came to the policy.which is giving me empty array in the ejs

Policy

module.exports = function (req, res, next) {
try {
    if (sails.config.views.locals.HeaderData == 'undefined' || sails.config.views.locals.HeaderData == 'is not defined' || sails.config.views.locals.HeaderData == undefined) {
        sails.config.views.locals.HeaderData = [];
    }
    if (_.isEmpty(sails.config.views.locals.HeaderData)) {
        MenuItems.getMenuItems('items', function (err, response) {
            if (err) {
                sails.log.debug(err);
            }
            else {
                sails.config.views.locals.HeaderData = response[0].dataValues;
            }
        })
    }
}
catch (e) {
    console.log("errrrrr", e);
}
next();

}

Sam77
  • 21
  • 3

1 Answers1

3

next() is called before MenuItems.getMenuItems might have finished. So move the next() statement inside the callback:

MenuItems.getMenuItems('items', function (err, response) {
    if (err) {
        sails.log.debug(err);
    }else{
        sails.config.views.locals.HeaderData = response[0].dataValues;
    }
    next();
})
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601