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 app...

问题:

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);        
    })
};

回答1:

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

  • 发表于 2019-01-23 02:46
  • 阅读 ( 177 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除