0

I am trying to iterate through an array of categoryIds to return an array of Category items which I want to populate in my categories field. However, despite iterating through the array of categoryIds successfully, I still get an empty array. I looked. through my codes several times and it looks fine to me. Anyone can help me here?

I have numbered the output of console.log(categories) and described the console log. The problem exists between 1 & 2. 1 was able to successfully populate the array. However, once it breaks outside the forEach, 2 returns an empty array. Why is it so? Shouldn't the array be populated already? Thanks in advance

      let categories: Category[] = [];
try {
  categoryIds.forEach(async (categoryId) => {

    const category = await Category.findOne({ where: { id: categoryId } });

    if (category) {
      categories.push(category);
    }

    console.log("1", categories); // [ { category } { category } ] OK
  });
  console.log("2", categories);  // []

  if (categories.length === 0) {
    return null;
  }

  console.log("3", categories);  // Never reach because categories.length === 0


  const newQuestion = new Question();
  newQuestion.title = title;
  newQuestion.text = text;
  newQuestion.categories = categories;
  const question = await newQuestion.save();
  return question;
} catch (error) {
  console.log(error);
  return null;
}
Hendry Lim
  • 1,929
  • 2
  • 21
  • 45
  • Thanks. However, I'm already using async and await for my foreach loop – Hendry Lim Apr 29 '20 at 11:53
  • 1
    Not familiar with the following methods: `.findOne()` and `.save()` Is this code incomplete? – zer00ne Apr 29 '20 at 12:06
  • @HendryLim read more carefully VLAZ' link. The problem is not that you miss async in forEach the problem **IS** that async in forEach does not work the way you expect – grodzi Apr 29 '20 at 12:06
  • Hi @HendryLim, you should `await` the `async` callback – Konstantin A. Magg Apr 29 '20 at 12:06
  • 1
    `console.log("2", categories); ` is placed outside the scope of whatever it is (part of `class Category`?). `console.log("1", categories);` is in the same brackets as where `let categories = ...` is defined -- whereas `console.log("2", categories); ` and `console.log("3", categories);` is not. – zer00ne Apr 29 '20 at 12:14
  • @grodzi. You are right grodzi. It works now. Thanks – Hendry Lim Apr 29 '20 at 12:33

0 Answers0