Express异步错误处理问题



我正在努力避免路由处理程序中的try-catch块。我正试图以以下方式捕捉错误:

const catchAsync = (fn) => {
// why this function does not have access to req,res,next?
// I am passing async(req,res,next) as an argument, hence
// req,res,next should be known to this function
fn(req, res, next).catch((err) => next(err));

};

然后在路由处理程序中:

exports.createTour = catchAsync(async (req, res, next) => {
const newTour = await Tour.create(req.body);
res.status(201).json({
status: "success",
data: {
tour: newTour,
},
});
});

现在的问题是,我不明白为什么catchAsync函数块中的函数fn(req,res,next)在调用时不能访问(req,res,next)?我所理解的是,我将async(req,res,next)作为参数传递给catchAsync函数。因此,当函数在catchAsync块内被调用时,它应该可以访问req,res,next

req,res,nextfn函数的参数。这些变量是函数自身执行上下文的局部变量。当调用函数时,应该为这些参数变量提供。您无法访问这些变量本身,因为在执行调用之前它们还不存在。

最新更新