I'm using a many to many relation with TypeOrm who is needing Ids to find the subcategories of an article.
The problem is that the map is not awaiting to push the result in the array.
Here is my map function with the list and the logs:
const subcategories = articleDto.subcategoriesIds.split(',').map(x => +x)
const subcategoriesList = []
await subcategories.map(async (subcategoryId) => {
console.log('start:' + subcategoryId)
const category = await this.subcategoriesService.getSubcategoryById(subcategoryId);
console.log('mid:' + subcategoryId)
await subcategoriesList.push(category);
console.log('end:' + subcategoryId)
});
console.log('### ' + subcategories);
console.log('### ' + subcategoriesList);
Here is the output of the logs:
start:2
start:3
### 2,3
###
mid:2
end:2
mid:3
end:3
I'm not understanding why the result is not awaited, thanks for the help if you know how to manage with this problem.
EDIT: Solved this issue by adding a Promise.all
using map inside
const subcategories = articleDto.subcategoriesIds.split(',').map(x => +x);
const subcategoriesList = await Promise.all(subcategories.map((subcategoryId) => {
return new Promise((resolve => {
this.subcategoriesService.getSubcategoryById(subcategoryId).then(result => {
resolve(result);
});
}))
}));