Is it possible to call an async middleware inside of another async middleware in Express.js?
Whenever I try to do so, it doesn't execute in the order I would like it to.
I want them to execute in order and have an output of First, Second, Third
.
Could anyone explain why or how I can achieve what I'm trying to?
const first = async (req, res, next) => {
console.log('First');
next()
}
const second = async (req, res, next) => {
await first(req, res, next);
console.log('Second');
next();
}
router.get('/logs', second, async (req, res) => {
console.log('Third');
res.send('Done');
});
// Console Output:
// First
// Third
// Second
If I don't execute first()
inside of second()
it works just fine, but for something I'm doing I want to be able to execute the middleware inside of the other.
const first = async (req, res, next) => {
console.log('First');
next()
}
const second = async (req, res, next) => {
console.log('Second');
next();
}
router.get('/logs', first, second, async (req, res) => {
console.log('Third');
res.send('Done');
});
// Console Output:
// First
// Second
// Third
CodePudding user response:
You passed next
to the first
function, which will call the route handler, instead of second
code
You have to pass a new callback
const first = async (req, res, next) => {
console.log('First');
next()
}
const second = async (req, res, next) => {
await first(req, res, () => {
console.log('Second');
next();
});
}
router.get('/logs', second, async (req, res) => {
console.log('Third');
res.send('Done');
});
or
const first = async (req, res, next) => {
console.log('First');
next()
}
const second = async (req, res, next) => {
await new Promise(r => first(req, res, r))
console.log('Second');
next();
}
router.get('/logs', second, async (req, res) => {
console.log('Third');
res.send('Done');
});