Nodejs - pass a function in the format of Privileges to async await

Asked

Viewed 42 times

-1

I have the code of an application made a while ago, but it was made using Promises, then/catch, I’m trying to familiarize myself with async await but I’m having difficulties,I would like to see how this code would look in the form of async await. follows the code(ps: I am using Mongoose):

const productsModel = require("../models/ProductsModel");

exports.getDashboard = (req, res, next) => {
    let category = req.query.category;
    let validCategories = ["Computadores", "Joysticks", "Monitores"];
    let productsPromise;
    if (category && validCategories.includes(category))
        productsPromise = productsModel.getProductsByCategoria(category);
    else productsPromise = productsModel.getAllProducts();
    productsPromise
        .then(products => {
            res.render("inicio", {
                products: products,
                isUser: req.session.userId,
                isAdm: req.session.isAdm,
                validationError: req.flash("validationErrors")[0],
                pageTitle: "Dashboard"
            });
        })
        .catch(err => {
            console.log(err);
        });
};

  • I don’t know if this is part of the scope of the site, but you can see an example here

1 answer

0


Hello, good morning, kindly follow a possible solution...

exports.getDashboard = async(req, res, next) => {
  const category = req.query.category;
  const validCategories = ["Computadores", "Joysticks", "Monitores"];
  const hasCategory = category && validCategories.includes(category);   
  const {isUser, isAdmin} = req.sessions;
   
 try {

    const products = hasCategory ? 
       await productsModel.getProductsByCategoria(category) :
       await productsModel.getAllProducts();
 
   res.render({
            products,
            isUser,
            isAdmin,
            validationError: req.flash("validationErrors")[0], 
            pageTitle: "Dashboard"
       });

   }catch(err) {
      console.log(err);
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.