1

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

1 Answer 1

2

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');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow, it worked! Thank you, you are incredible. Are you able to go into a bit of a more in-depth explanation as to why you wouldn't pass in next to the middleware and add it to your answer? Also, am I able to use async for that callback function replacing the next?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.