In order to find the subcategories of an article, I am utilizing a many-to-many relationship with TypeOrm that requires Ids.
However, I encountered an issue where the map function is not properly waiting to push the results into the array.
Below is the code snippet featuring the map function along with the list and corresponding 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);
The log output is as follows:
start:2
start:3
### 2,3
###
mid:2
end:2
mid:3
end:3
I'm puzzled as to why the result is not being awaited. Any assistance on resolving this issue is greatly appreciated.
EDIT: Resolved the issue by incorporating Promise.all
within the map function:
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);
});
}))
}));