I want to combine middlewares in express to make them parallel, as opposed to sequential if you put the in app.use(path, /* middlewares *,/ callback)
.
I write the following function:
function makeParallelMiddleware(args) {
let makePromises = (req, res) => args.map((func) => {
return new Promise((resolve, reject) => {
console.log('In promise: ' + func.name);
func(req, res, resolve);
})
});
return (req, res, next) => Promise.all(makePromises(req, res)).then(next())
}
But this does not seem to work properly. I test with the following two middlewares:
function middlewareA(req, res, next) {
req.A = 1;
console.log('I am in A');
setTimeout(() => {
console.log('I am in A delay');
if (req.C) {
req.C = 'BA'
} else {
req.C = 'A'
}
next()
}, 1000)
}
function middlewareB(req, res, next) {
req.B = 1;
if (req.C) {
req.C = 'AB'
} else {
req.C = 'B'
}
next()
}
app.get('/parallel', makeParallelMiddleware([middlewareA, middlewareB]) ,(req, res) => {
res.send(req.C);
});
When I access /parallel
, I can only get "B" instead of "BA".
How can it be possible that the promise is resolved before req.C
is set? How do I correct this to get the desired result?