似乎没有内置的方法可以做到这一点,但你可以通过一个小技巧来获得相同的结果。创建您自己的中间件数组(我们称之为dynamicMiddleware),但不要将其推送到 express 中,而是仅推送 1 个中间件,它将异步并按顺序执行 dynamicMiddleware 中的所有处理程序。
const async = require('async')
// Middleware
const m1 = (req, res, next) => {
// do something here
next();
}
const m2 = (req, res, next) => {
// do something here
next();
}
const m3 = (req, res, next) => {
// do something here
next();
}
let dynamicMiddleware = [m1, m2, m3]
app.use((req, res, next) => {
// execute async handlers one by one
async.eachSeries(
// array to iterate over
dynamicMiddleware,
// iteration function
(handler, callback) => {
// call handler with req, res, and callback as next
handler(req, res, callback)
},
// final callback
(err) => {
if( err ) {
// handle error as needed
} else {
// call next middleware
next()
}
}
);
})
代码有点粗糙,因为我现在没有机会测试它,但想法应该很清楚:将所有动态处理程序数组包装在 1 个中间件中,它将循环遍历数组。当您向数组添加或删除处理程序时,只会调用数组中剩下的处理程序。