Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading