Here I had created mongoose model name Tour. I am not able to get how is try/clause can be removed by refactoring the code?Can anyone please help me to understand how is both the code same!
const createTour = async (req, res) => {
try {
const tour = await Tour.create(req.body)
res.status(201).json({
status: 'Success',
data: {
tour,
},
})
} catch (err) {
res.status(400).json({
status: 'fail',
message: err,
})
}
}
Later refactored code is as below -
const catchAsync = function (fn) {
const inner = function (req, res, next) {
return fn(req, res, next).catch(next)
}
return inner
}
const createTour = catchAsync(async (req, res) => {
const tour = await Tour.create(req.body)
res.status(201).json({
status: 'Success',
data: {
tour,
},
})
})
I am not abled to understand why both code are working same?