I'm currently building an API and I looked for a way to refactor the async functions so that I don't always have to write try{ } catch(err).... I found this code and there are some things I really do not understand:
module.exports = function (cb) {
return function (req, res, next) {
cb(req, res, next).catch(next);
};
};
First of all why does the returning function gets access to the req, res, next parameters? I think it has something to do with closures, but i can really not see why this works.
Also why do we have to return a function in order to get the parameters? Couldn't we just also use the parameters in the callback function? Like this:
module.exports = function (cb) {
cb(req, res, next).catch(next);
};
Second, why can we just say ... .catch(next), how does the next() function get access to the error from the catch block without having to pass it in?
Because this is how I would've done it:
... .catch((err) => next(err));
This is how I'm using this function:
exports.getAllTasks = catchAsync(async (req, res, next) => {
const tasks = await Task.find();
if (tasks.length === 0) throw new Error('No tasks found');
res.status(200).json({
status: 'success',
results: tasks.length,
data: {
tasks,
},
});
});