2

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);        
    })
};
anderwald
  • 139
  • 3
  • 9
  • 7
    What exactly do those "object changes" look like? – Pointy Jan 21 '19 at 22:03
  • how do you retrive results from that promise? – Kamil Kiełczewski Jan 21 '19 at 22:09
  • 1
    Why are you using promises at all here? In the code you posted, there's nothing asychronous. – Bergi Jan 21 '19 at 22:11
  • '/*Doing some object changes in this loop*/' is this async ? – M. Gara Jan 21 '19 at 22:15
  • 1
    you don't need to use Promise in this case, there's nothing asynchronous – ggirodda Jan 21 '19 at 22:17
  • I have inserted one of the changes. These changes are all done "locally" without going for an API call. I am new to promises so correct me if i am wrong: i used promises because i called "evaluateQuiz" in another function with the "await" keyword. – anderwald Jan 21 '19 at 22:18
  • @a_nicewood, unless you are looping the wrong way, there is no problem with your snippet. – M. Gara Jan 21 '19 at 22:18
  • you have to do this to ge tthe function result `let quiz = await evaluateQuiz(players)`, or `evaluateQuiz(players).then(result => { console.log(result) })` – ggirodda Jan 21 '19 at 22:22
  • no, that's not the correct way. `console.log(evaluateQuiz(players))` gives you an instance of Promise, not the result. You have to `await` for the result, or use `then`. See my exemple in the comment before – ggirodda Jan 21 '19 at 22:24
  • @ggirodda, yes. This is also the way i defined to call evaluateQuiz. I have the following snipped at the end of the other function: let quiz = await evaluateQuiz(players) console.log(quiz); return quiz; The object quiz which is displayed in the console is fine, but the one i am getting in my response in Postman does not contain the object changes from the loop... – anderwald Jan 21 '19 at 22:25
  • Ok so the problem it's not `Promise`, maybe you have to investigate why the response you get it's not what you expect, or post more code if you want more help. The way you use Promise is the correct way – ggirodda Jan 21 '19 at 22:29
  • I assumed that you use Promise in the code you posted just for exemple pourpose. If this is really your code you don't need to use Promise, there's nothing async – ggirodda Jan 21 '19 at 22:32
  • @a_nicewood excellent that you found the solution, the subject of conversation are promises if my answer or any other one solved your issue, please mark it as accepted. Happy to help, and welcome to Stack Overflow. – ccordon Jan 21 '19 at 23:14

1 Answers1

2

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

ccordon
  • 1,072
  • 12
  • 22
  • Thanks a lot ccordon. I edited my post to give you more information about my problem. 1) You are right, i dont need a promise in this case. 2) could have a look at my other class? Im not sure why my postman response differs from a console.log entry from the same object... – anderwald Jan 21 '19 at 22:39
  • 1
    @a_nicewood But you don't need that `await` on the `evaluateQuiz()` call in the first place! There's nothing asynchronous, you need neither a promise here nor await aynthing. – Bergi Jan 21 '19 at 22:42