简体   繁体   English

返回带有回调参数 function 的 function

[英]Returning a function with with the parameters of a callback function

Consider this function:考虑这个 function:

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

In the first returned function, it says:在第一个返回的 function 中,它说:

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

Now, to my knowledge, ...args would be exactly one thing: 'handler' It wouldn't be the parameters to the callback because those aren't the arguments to catchAsync, they are the arguments to the callback function 'handler'.现在,据我所知,...args 将完全是一件事:'handler' 它不是回调的参数,因为那些不是用于 catchAsync 的 arguments,它们是 arguments 的回调 ZC1C425268E68394D1AB5074'C . Is there something I didn't learn about arguments of a callback being passed to the original function?关于传递给原始 function 的回调的 arguments 有什么我没有了解的吗?

Thanks!谢谢!

catchAsync is a function which returns another function. catchAsync是一个 function,它返回另一个 function。 The outer function and the inner function each get passed different things.外部 function 和内部 function 每个都通过了不同的东西。 You would use this code something like the following:您将使用如下代码:

const handlerWithCatch = catchAsync(someHandlerFn);
handlerWithCatch(someRequest, someResponse, someNextFn);

// Or on a single line:
catchAsync(someHandlerFn)(someRequest, someResponse, someNextFn)

On the insider handler will contain someHandlerFn , and args will be an array of [someRequest, someResponse, someNextFn]内部handler将包含someHandlerFn ,而args将是[someRequest, someResponse, someNextFn]的数组

Just re-read your question 1000 times.只需重新阅读您的问题 1000 次。

As you mention ...args is not the argument of catchAsync.正如您提到的...args不是catchAsync 的论点。 This function is how you implement the Strategy design pattern in Javascript.这个 function 是您在 Javascript 中实现策略设计模式的方式。

catchAsync itself will return a function that you will call with req,res,next catchAsync 本身将返回一个 function ,您将使用 req,res,next 调用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM