0

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');
    });
});
3
  • You should definitely switch to async/await. This is the ultimate callback hell solution. Commented Apr 19, 2020 at 12:06
  • You seems to miss Your Blog fetching from database , but using allBlogs as variable. Commented Apr 19, 2020 at 12:26
  • The Blog fetching is done outside this route Commented Apr 19, 2020 at 12:34

1 Answer 1

1

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');
   }
)};
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thanks a lot for your answer. I didn't learn async/await yet but this seems to get rid of code indentation problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.