Home > OS >  Array empty even when its value was already set with a push
Array empty even when its value was already set with a push

Time:07-10

I´m getting all the categories from my database, then I'm selecting all the posts that that category has, then I'm trying to push into an array a new customized object, but the push only works in the for cycle, when I try to return the array it is empty, but if the array is inside of the for it has values.

enter image description here

Why is the array empty outside of the for if I already give it a push inside of the for

CodePudding user response:

Even though you didn't upload your code directly to the question body, I'll try to answer that with code examples.

You're most likely facing this issue because you return a response before it is completely processed. Your Post.find function is asynchronous, but you don't wait for them to complete.

Try this one.

Category.find().then(Categories => {
    const asyncTasks = Categories.map((category) => {
        return Post.find ({categories: category.id}).then(Posts => {
            posts.push({
                id: category.id,
                category_name: category.category_name,
                posts_number: Posts.length
            });
        });
    });
    Promise.all(asyncTasks).then(() => {
        res.status(200).json(posts);
    });
});
  • Related