javascript 节点js数组未更新

zxlwwiss  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(138)

嗨,这是我的函数,我从我的控制器调用它,如下所示:var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id);但是我在控制器中得到空数组作为结果,但是当我在我的模型中记录结果时,它返回包含两个对象的数组的数据?我在哪里犯了错误,有人能帮助吗?

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;
}```
y1aodyip

y1aodyip1#

当使用mapforEach等在数组上迭代时,使用async/await不会执行您期望的操作。所有迭代都将在调用totalvotesbypolloption之前完成,即使是一次。
map替换为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);
    }

相关问题