After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file:
const asyncHWrapper = (fn) => {
return async (req, res, next) => {
try {
await fn(req, res, next);
} catch (error) {
next(error);
}
};
};
module.exports = asyncHWrapper;
Here is how it is used:
const Task = require("../models/taskModel");
const asyncWrapper = require("../middleware/async");
const { createCustomError } = require("../errors/customErrors");
const getAllTasks = asyncWrapper(async (req, res) => {
const tasks = await Task.find({});
res.status(200).json({ tasks });
});
I have some questions that are confusing me:
- Is it necessary to return an arrow function in the asyncWrapper? Why not just call the function directly?
- Where do the parameters (req, res) in the asyncWrapper function come from? Are they from the "fn" function declaration?
- Why should two pairs of async and await be written in the wrapper and when calling it?
Thank you for any help! The tutorial link: Node.js / Express Course - Build 4 Projects