What is the best way to write it? Node.JS

this is my first post : ) Someone can help me to improve my code to get a better way to write it?

Temporada.findAll({
  where: { status: 1 }
}).then(temporadas => {


  Temporada.count({
    where: { status: 1 }
  }).then(temporadasAbertas => {
    if (temporadasAbertas > 0) {
      if (user_logged_acesso == 1) {
        JogoContagem.findAll({
          where: {
            j1Id: user_logged_id,
            status: { [Op.ne]: 0 }
          }
        }).then((blockeds) => {
          console.log(blockeds)
          res.render("painel/jogos/new", { users, user_logged_id, temporadas, blockeds });
        })
        
      } else {
        req.flash("error_msg", "No momento você não tem premissão de cadastrar jogos.");
        res.redirect("/painel");
      }
      
    } else {
      req.flash("error_msg", "No momento não há temporadas em aberto para cadastar jogos.");
      res.redirect("/painel");
    }
  })
  
})

It's working well, however I know that exist a better way to write it, maybe using functions with async await, but I don't know how to collect the results and insert the results to res.render. I guess I need to create a var with array... Anyway I suppose it... If you know a way let me know to I improve it.

Observation: My code have a few parts written in English and Portuguese, just if someone read and be curious to know which language. ( \o/ Hello from BRASIL )

thanks a lot,

Kind regards Davi Soares

Upvotes: 0

Views: 73

Answers (2)

Updated code:

router.get("/painel/jogos/new", authenticator, (req, res) => {
        var json = req.session.user;
        var user_logged = JSON.stringify(json);
        var user_logged = JSON.parse(user_logged);
        var user_logged_id = user_logged.id;
        var user_logged_acesso = user_logged.acesso;

        async function load() {
                try {
                        const loadUsers = await User.findAll({ where: { acesso: 1 }, order: [ ['primeiro_nome' , 'ASC'] ] })
                        const loadTemporadas = await Temporada.findAll({ where: { status: 1 } })
                        if (loadTemporadas[0] == null) { req.flash("error_msg", "No momento não há temporadas em aberto para cadastar jogos."); res.redirect("/painel"); }
                        const loadBlockeds = await JogoContagem.findAll({ where: { j1Id: user_logged_id, status: { [Op.ne]: 0 } } })

                        res.render("painel/jogos/new", { users: loadUsers, user_logged_id, temporadas: loadTemporadas, blockeds: loadBlockeds });
                } catch (err) {
                        console.log(err)
                        req.flash("error_msg", "Ocorreu algum erro ao carregar a página, favor informar o administrador do site. ERROR CODE: /painel/jogos/new - LOAD"); 
                        res.redirect("/painel");
                }
        }
        load()
})

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

This is how you could do that with await. Inside an async function, do:

const temporadas = await Temporada.findAll({
  where: { status: 1 }
});
const temporadasAbertas = await Temporada.count({
  where: { status: 1 }
});
if (temporadasAbertas <= 0) {
  req.flash("error_msg", "No momento não há temporadas em aberto para cadastar jogos.");
  res.redirect("/painel");
  return;
}
if (user_logged_acesso !== 1) {
  req.flash("error_msg", "No momento você não tem premissão de cadastrar jogos.");
  res.redirect("/painel");
  return;
}
const blockeds = await JogoContagem.findAll({
  where: {
    j1Id: user_logged_id,
    status: {
      [Op.ne]: 0
    }
  }
});

res.render("painel/jogos/new", { users, user_logged_id, temporadas, blockeds });

Make sure to .catch errors too, either in a catch of a try/catch, or in a .catch onto the function call.

Upvotes: 4

Related Questions