返回带有回调函数参数的函数



考虑这个函数:

export const catchAsync = (handler) => 
(...args) => 
^^^^ why are these the parameters to handler, and not catchAsync?
handler(...args).catch(args[2]);

在第一个返回的函数中,它说:

(...args: [Request, Response, NextFunction]) => 

现在,据我所知。。。args完全是一回事:"handler"它不会是回调的参数,因为它们不是catchAsync的参数,而是回调函数"handle"的参数。关于传递给原始函数的回调参数,有什么我没有学到的吗?

谢谢!

catchAsync是一个返回另一个函数的函数。外部函数和内部函数各自传递不同的东西。您可以使用以下代码:

const handlerWithCatch = catchAsync(someHandlerFn);
handlerWithCatch(someRequest, someResponse, someNextFn);
// Or on a single line:
catchAsync(someHandlerFn)(someRequest, someResponse, someNextFn)

在内部handler将包含someHandlerFn,而args将是[someRequest, someResponse, someNextFn]的阵列

只需将您的问题重读1000遍。

正如您所提到的,...args不是catchAsync的参数。这个函数是如何在Javascript中实现Strategy设计模式的。

catchAsync本身将返回一个函数,您将使用req、res和下一个调用该函数

catchAsync(handler)(req,res,next);

最新更新