手动链接Express中间件

我目前使用2个中间件:

Express-jwt ,它从请求中提取/validationJsonWebToken,我自己的中间件检查JWT是否包含特定的信息(权限)。

我想一起有条件地使用这些中间件(根据路线上是否有特定的招牌属性)。

我想要做这样的事情:

let expressjwt = function(req, res, next) { ... }; let jwtValidator = function(req, res, next) { ... }; app.use((res, req, next) => { if(req.swagger.someAttribute) { expressjwt(req, res, jwtValidator(req, res, next)); // The issue here is that jwtValidator will get called even if // expressjwt produces an error } else { next(); } }); 

这听起来像是一个问题 – “如果服务A成功,你如何有条件地调用服务B.

这是承诺的主要目标之一 – 它允许您连接asynchronous调用,并有条件地“解决”。 如果需要,我可以发布代码示例。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

我结束了使用Promise.fromCallback从内存中包装我的第一个中间件在一个Promise中,像这样:

 if (req.swagger.someAttribute) { Promise.fromCallback(cb => expressjwt(req, res, cb)) .then(() => { return jwtValidator(req, res, next); }) .catch(next); // Or deal with the rejection } else { next(); } 

Promise.fromCallback非常有用,因为如果中间件失败, next()只会被调用,因此将成为promise.reject