anderwald
anderwald

Reputation: 149

Promises: Resolve returns value too early

UPDATE: The source of my problem was, that i was assigning values to my array by their uuid. so i.e. quiz[uuid] = x. Therefore the array length is 0 and the property is apparently not processed within a json response.

I am building a function where I initialize the object quiz and alter it within a for loop. When i am done i want to resolve the promise. When i call this function I only receive the intialized values and lack the changes from the for loop. console.log(quiz) logs the object with the changes. I cant find my error...

I tried some if clauses to only call the resolve function when the for loop is done. This led either the same result or to no response.

app.get('/playQuiz', function (req, res) {
    playQuiz().then(data => {
        res.status(200).json({
            quiz: data
        });
    });    
});

async function playQuiz(){
    var players = {
        puuids: [],
        stats: []
    }
    credentials = await getCredentials();

    token = credentials.token;
    port = credentials.port;

    players.puuids = await getLobby(port, token);
    for(i=0; i<players.puuids.length; i++){
        players.stats[i] = await getStats(port, token, players.puuids[i])
    }

    let quiz = await evaluateQuiz(players)
    console.log(quiz); // This displays the object quiz with the changes from the loop
    return quiz; //The response i get displayed in Postman from this line, does not show the changes in i.e. csScore. It only shows an empty array.
}

function evaluateQuiz(players){
    return new Promise((resolve, reject) => {
        var quiz = [{
                questionId: 1,
                question: "Who has the most cs per game?",
                csScore: []
            },
            {
                questionId: 2,
                question: "Who has the highest vision score per game?",
                vsScore: []
            },
            {
                questionId: 3,
                question: "Who has the best win rate?",
                winRate: []
            },
            {
                questionId: 4,
                question: "Who has the most quadra kills?",
                quadraKills: []
            },
            {
                questionId: 5,
                question: "Who has the highest objective participation?",
                objectiveRate: []
            }
        ]

        for(var i=0; i<players.puuids.length; i++){
            quiz[0].csScore[players.puuids[i]] = players.stats[i].csScore /    players.stats[i].gamePlayed;
            quiz[1].vsScore[players.puuids[i]] = players.stats[i].visionScore / players.stats[i].gamePlayed;
            quiz[2].winRate[players.puuids[i]] = players.stats[i].victory / players.stats[i].gamePlayed;
            quiz[3].quadraKills[players.puuids[i]] = players.stats[i].quadraKills / players.stats[i].gamePlayed;
            quiz[4].objectiveRate[players.puuids[i]] = players.stats[i].objectiveTakenInvolved / players.stats[i].gamePlayed;
        }
        //console.log(quiz);
        resolve(quiz);        
    })
};

Upvotes: 2

Views: 90

Answers (1)

ccordon
ccordon

Reputation: 1102

Promises and callbacks are used when asynchronous processes are performed in this case since what you do is a simple calculation you don't need to make use of promises.

This would be the solution to your code, welcome to StackOverflow and happy coding!

function evaluateQuiz(players) {
    const quiz = [{ ...}]

    for (var i = 0; i < players.puuids.length; i++) {
        // Doing some object changes in this loop like: 
        quiz[0].csScore[players.puuids[i]] = players.stats[i].csScore / players.stats[i].gamePlayed;
    }
    return quiz;
};

Read article so that you better understand the use of Promises

Upvotes: 2

Related Questions