const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((error) => {
res.status(500).json({ message: error });
});
};
export default asyncHandler;
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((error) => {
res.status(500).json({ message: error });
});
};
export default asyncHandler;
Can you provide some context about where you found this code? It doesn’t look the ExpressJS middleware code we have in the curriculum.
It looks like a wrapper function for handling async handlers (sort of promisify type stuff).
Looks similar and has code comments
https://gist.github.com/ZeeshanMukhtar1/ae9e046241a29f4d2d2ed86a5df94ccc
asyncHandler
takes a callback fn
(presumably a handler) and returns a middleware function (it has next
) that when invoked will call the callback with the provided arguments (the parameters of the returned middleware function) and pass the callback return value to resolve
. If it throws, it will send a 500 and a JSON response. Or something like that.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.