Using promises with mongoose functions

I'm new to promises. And I'm trying to use them with mongoose query functions like find() and findById(). Everything seems to work but I'm not sure if this is the correct way of chaining then. The objective of using promises is to eliminate callback hell but the way I'm chaining then looks very similar to callbacks. Is there a better way to write this route?

router.get('/homehr/employees/new', middleware.isLoggedInAsHR, (req, res) => {
Department.find({})
    .exec()
    .then((allDepartments) => {
        Employee.findById(req.user.employee.id)
        .exec()
        .then((foundEmployee) => {
            res.render('hr/employees/new', {
                departments: allDepartments,
                employee: foundEmployee,
                blogs: allBlogs
            });
        });
    })
    .catch((err) => {
        console.log(err);
        req.flash('error', err.message);
        return res.redirect('back');
    });
});

Upvotes: 0

Views: 31

Answers (1)

Gaurav
Gaurav

Reputation: 543

Your Routes doesn't seems to have dependency of fetching models in sequence. So You can write this in more better way as follow:

router.get('/homehr/employees/new', middleware.isLoggedInAsHR, async (req, res) => {
   try{
      const allDepartments = await Department.find({});
      const foundEmployee = await Employee.findById(req.user.employee.id);
      res.render('hr/employees/new', {
          departments: allDepartments,
          employee: foundEmployee,
          blogs: allBlogs
      });
   }catch(err){
       console.log(err);
       req.flash('error', err.message);
       return res.redirect('back');
   }
)};

Upvotes: 1

Related Questions