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

Node js array not getting updated

Hi this is my function i am calling this from my controller like this:
var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id);
but i am getting empty array as result in controller but when i logged result in my model it is returning the data of array containing two objects ? where i am doing mistake can someone help?

const getPollOptionsByPollId = async (poll_id) => 
{
    var querySql1 = "SELECT * FROM public.group_poll_options 

                     WHERE option_poll_id= $1 AND 

                    option_status = $2 ORDER BY option_id";

    var queryParams1 = [poll_id, "active"];
    var pollOptions = await db.query(querySql1, queryParams1);
    var result = [];
    if (pollOptions.rowCount != 0) {


        pollOptions.rows.map(async value => {
            var voteCount = await totalvotesbypolloption(poll_id, value.option_id);
            console.log("voteCount",voteCount);
            var data = {
                option_id: value.option_id,
                option_poll_id: value.option_poll_id,
                option_value: value.option_value,
                option_status: value.option_status,
                option_created_at: value.option_created_at,
                option_votes: voteCount
            }

            result.push(data);
        });

    }
    return result;
}```

>Solution :

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

Using async/await when iterating over arrays with map, forEach, etc, doesn’t do what you expect it to do. All iterations will finish before totalvotesbypolloption is called even once.

Replace map with with for...of:

    for (const value of pollOptions.rows) {
        var voteCount = await totalvotesbypolloption(poll_id, value.option_id);
        console.log("voteCount",voteCount);
        var data = {
            option_id: value.option_id,
            option_poll_id: value.option_poll_id,
            option_value: value.option_value,
            option_status: value.option_status,
            option_created_at: value.option_created_at,
            option_votes: voteCount
        }

        result.push(data);
    }
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