I am unable to iterate the array

Asked

Viewed 26 times

-1

I would like to popular this array with the Category object I get when I query findById. But the variable loggedUserCategories appears as an empty array in Sponse , however, I can visualize the console.log(category);

        let loggedUserCategories = [];

        
        categoriesId.forEach(async(id) => {
            
            const category =  await CategoryModel.findById(id);
            loggedUserCategories.push(category)
            console.log(category);

        });

      res.send(loggedUserCategories);

1 answer

2


Your code has no difference with the code below:

let loggedUserCategories = [];
res.send(loggedUserCategories);
categoriesId.forEach(async(id) => {
    const category =  await CategoryModel.findById(id);
    loggedUserCategories.push(category)
    console.log(category);
});

Try it like this:

async () => {
    let loggedUserCategories = [];
    categoriesId.forEach(async (id) => {
        const category = await CategoryModel.findById(id);
        loggedUserCategories.push(category)
        console.log(category);
    });
    res.send(loggedUserCategories);
}

Or waiting for the names each await creates:

let loggedUserCategories = [];
const promises = categoriesId.map(async (id, idx) => {
    category = await CategoryModel.findById(id);
    loggedUserCategories.push(category);
    console.log(category);
});
await Promise.all(promises);
res.send(loggedUserCategories);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.