Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
How do I make the router not render before all queries in a loop are done? (mongoDB)

I have this router: // get your courses page

router.get('/yourcourses', async (req, res, next) => {
  let results = []
  if(req.user){
    for(let i =0; i<req.user.coursesFollowing.length; i++){
      let course = Course.findOne({ 'published': true, title: req.user.coursesFollowing[i].courseTitle, authorUsername: req.user.coursesFollowing[i].username }).exec(function (err, result) {
        if(err){return next(err)}
        results.push(result)
        console.log(results)
      })
    }
  }
  console.log(results)
  res.render('content', { whichOne: 1, user: req.user, courses: results});
});

I console log the result from the queries it seems to find the right documents, and when i console log the full array it seems okay,

however looking at the terminal I can see the computer prints the values after rendering the page, which means I need to use an async function to wait for the queries to end, however I am used to do it with one query, not multiple queries inside a loop, so how do I do that?

How do I wait until all the queries inside a loop are done before rendering the page? I tried using settimeout() however it is not predicting how much time it will take. how would I fix this?

THANKS

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!