简体   繁体   English

从 JavaScript 中的循环返回一个值?

[英]Return a value from loop in JavaScript?

I was creating a function to delete indexes that do not match the required amount of "levels" in my database, then return that array.我正在创建一个 function 来删除与我的数据库中所需的“级别”数量不匹配的索引,然后返回该数组。

The problem is when I do cleanWinners(winners, guild).then(res => console.log(res)) I receive undefined.问题是当我执行cleanWinners(winners, guild).then(res => console.log(res))时,我收到未定义的消息。 I assume the code is not waiting for this function to end before returning the array?我假设代码在返回数组之前没有等待这个 function 结束? How can I fix that?我该如何解决?

When I use this code:当我使用这段代码时:

async function cleanWinners(winners, guild) {
    let returnedArray;

    for (const winner of winners) {
        XP.findOne({serverID: guild.id, userID: winner}, (err, xpTable) => {
            if (err) throw err;
            if (!xpTable) {
                const newXP = new XP({
                    totalXP: 0,
                    xp: 0,
                    level: 0,
                    date: 0,
                    serverID: guild.id,
                    userID: winner
                });
                newXP.save().catch(console.log);
                xpTable = newXP;
            }
            // If they have less than the set amount, get a new winner.
            if (xpTable.level < 1) {
                const index = winners.indexOf(winner);
                delete winners[index];
            }
            console.log('Removed less than level 1', winners);
            let newWinner = getWinners(winners, 1);
            winners = winners.concat(newWinner);
            console.log('New Winner array:', winners);
            returnedArray = winners;
        });
    }
    return returnedArray;
}
// 503418431861948418 should be removed, the other should stay.
// This code returns undefined before the loop even starts. I want this to run AFTER the loop has completed, no matter the amount of entries the array has.
cleanWinners(['209797091457761280','503418431861948418'], message.guild.id)
.then(res => console.log(res));

This is the result I get in my console:这是我在控制台中得到的结果:

undefined
Less than 1 level removed [ '209797091457761280', '503418431861948418' ]
New winners array [ '209797091457761280', '503418431861948418' ]
Less than 1 level removed [ '209797091457761280', <1 empty item> ]
New winners array [ '209797091457761280', <1 empty item> ]```

The problem is XP.findOne function is async and you passed a callback to it.问题是 XP.findOne function 是异步的,你向它传递了一个回调。 So it'll not wait for everything to finish before return returnedArray .所以它不会等到一切都完成后再return returnedArray You should use await on findOne await XP.findOne(... then your code will work in the way you're expecting it to.您应该在 findOne 上使用 await await XP.findOne(...然后您的代码将按照您期望的方式工作。

Here's a great mozilla link for async await if you want to check out https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await如果您想查看https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await ,这里有一个很棒的异步等待 mozilla 链接

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

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