Search code examples
javascriptnode.jsexpressmiddleware

why the underlying code gets executed in a block even after invoking next() in express?


exports.getTour = catchAsync(async (req, res, next) => {
  const tour = await Tour.findById(req.params.id);

  if (!tour) {
    next(new AppError('No tour found with that ID', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      tour
    }
  });
});

if tour variable is empty I am invoking the next() method and creating an error inside it using a class constructor but even after invoking the next() the response was sent as a response to the request, and then i am getting '[ERR_HTTP_HEADERS_SENT]:' error. Why the block is not exiting even after next is called?


Solution

  • Because you need to return in order to breakout of the function if tour is empty.

    So do this

    if (!tour) {
      return next(new AppError('No tour found with that ID', 404));  
    }