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

Returning a function with with the parameters of a callback function

考虑这个函数:

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 的参数,它们是参数到回调函数 'handler'。关于传递给原始函数的回调参数,有什么我没有学到的吗?

谢谢!

catchAsync是一个函数,returns是另一个函数。外部函数和内部函数分别传递不同的东西。您将使用如下代码:

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.

中实现策略设计模式的方式

catchAsync 本身将 return 一个您将使用 req,res,next

调用的函数
catchAsync(handler)(req,res,next);