Reputation: 17
blogCategorie and blog are both CRUD-objects. blogCatergorie.getAll
gives me all the category objects. I loop through each category and push the name of the category in to an array (categorieTitles). So far so good. In the map function i want to retrieve all the blogs from that category with blog.getBlogsFromCategory
, but it looks like the compiler ignores the await in front of this promise. It pushes the blogs at the end of the code when i already did the `console.log('Blog containers'). Did i do something wrong?
Code
let categorieTitles = [];
let blogContainers = [];
await blogCategorie.getAll().then((allCategories) => {
console.log('after 1st await');
allCategories.map(async (categorie) => {
categorieTitles.push(categorie.name);
await blog.getBlogsFromCategory(categorie.id).then((blogs) => {
console.log("after 2nd await");
let blogGroup = [];
blogs.map((blog) => {
blogGroup.push(blog);
});
blogContainers.push(blogGroup);
});
});
});
console.log('Categorie titels', categorieTitles);
console.log('Blog containers', blogContainers);
output
after 1st wait
Categorie titels [ 'Kinderen en psychologie', 'Efficiënt lesgeven' ]
Blog container []
after 2nd await
after 2nd await
Upvotes: 0
Views: 36
Reputation: 1651
async-await
inside a map do not work.
Also, if you are using await, then ideally you should not use the .then
syntax, since you can store the response of your asynchronous operation in a variable.
You can change the map
to a for-in
loop as below:
const allCategories = await blogCategorie.getAll();
console.log('after 1st await');
for (const categories of allCategories) {
categorieTitles.push(categorie.name);
const blogs = await blog.getBlogsFromCategory(categorie.id);
console.log("after 2nd await");
let blogGroup = [];
blogs.map((blog) => {
blogGroup.push(blog);
});
blogContainers.push(blogGroup);
};
Upvotes: 1