简体   繁体   English

承诺:过早地解决返回值

[英]Promises: Resolve returns value too early

UPDATE: The source of my problem was, that i was assigning values to my array by their uuid.更新:我的问题的根源是,我通过他们的 uuid 为我的数组赋值。 so ie quiz[uuid] = x.所以即测验[uuid] = x。 Therefore the array length is 0 and the property is apparently not processed within a json response.因此数组长度为 0 并且该属性显然未在 json 响应中处理。

I am building a function where I initialize the object quiz and alter it within a for loop.我正在构建一个函数,在其中初始化对象测验并在 for 循环中更改它。 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.当我调用这个函数时,我只收到初始化的值并且缺少 for 循环中的更改。 console.log(quiz) logs the object with the changes. console.log(quiz) 记录带有更改的对象。 I cant find my error...我找不到我的错误...

I tried some if clauses to only call the resolve function when the for loop is done.我尝试了一些 if 子句,只在 for 循环完成时调用 resolve 函数。 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);        
    })
};

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!这将是您代码的解决方案,欢迎使用 StackOverflow 并快乐编码!

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阅读文章,让你更好地理解Promises的使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM