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