0

I'm trying to find elements that contain specific values and push a certain value of those elements into a different array using a forEach loop.

app.get('/', async (req, res) => {
    const descriptions = await Description.find({});
    let tempDescriptions = [];
    let categoryClasses = [];
    descriptions.forEach(element => tempDescriptions.push(...element.category));
    categories = [...new Set(tempDescriptions)]
    categories.forEach async (function(element) {
      const description = await Description.findOne({category : element});
      categoryClasses.push(description.category[0]);
    });
    console.log(categoryClasses);
    res.render('home', { categories, categoryClasses })
});

But after I run this code, categoryClasses is still an empty array. I kind of get why this is happening, but I have no clue how to fix this. Any help would be greatly appreciated!

  • That code won't parse, you have `async` between `forEach` and `(function`, which is a syntax error. Re the `forEach`, see the linked question's answers for details, but `forEach` doesn't understand `async` functions so it finishes before those functions are done doing their work. Instead, use a `for-of` loop, see comments: https://pastebin.com/uicdJDf5 – T.J. Crowder Sep 28 '21 at 14:59
  • 1
    Thank you so much for the help! it works just like how I wanted it to :) – novicecoder Sep 29 '21 at 07:21

0 Answers0