简体   繁体   English

Express异步中间件

[英]Async middleware for Express

As we know, Express is not very good in handling async functions, in particular for the error handling. 众所周知,Express在处理异步功能方面不是很好,特别是在错误处理方面。

I did define an asyncMiddleware as follows: 我确实定义了asyncMiddleware,如下所示:

const asyncMiddleware = fn => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

And then: 接着:

router.get('/', asyncMiddleware(myRouteHandler))

Is there a way to properly rewrite the middleware in order to make it usable directly by the Express router? 有没有一种方法可以正确地重写中间件,以使其可以由Express路由器直接使用?

 router.use(asyncMiddleware)

Koa supports promises natively, it's expected that Express 5 will do this as well. Koa原生支持Promise,预计Express 5也将做到这一点。

Is there a way to properly rewrite the middleware in order to make it usable directly by the Express router? 有没有一种方法可以正确地重写中间件,以使其可以由Express路由器直接使用?

There is no way. 不可能。 In order to do that, Express app and router ( express.Router and express.Route classes) methods that use middlewares and route handlers should be monkey-patched to do what asyncMiddleware does. 为了做到这一点,应该对使用中间件和路由处理程序的Express approuterexpress.Routerexpress.Route类)方法进行修补,以实现asyncMiddleware功能。

Otherwise promise-based middlewares should be manually wrapped with a helper like asyncMiddleware . 否则,应使用类似于asyncMiddleware的帮助程序手动包装基于promise的中间件。

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

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