Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda