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;
}