从 JavaScript 中的循环返回一个值?
2020-06-19
186
我创建了一个函数来删除数据库中与所需“级别”数量不匹配的索引,然后返回该数组。
问题是,当我执行
cleanWinners(winners, guild).then(res => console.log(res))
时,我收到了未定义的结果。我假设代码没有等待此函数结束后再返回数组?我该如何解决这个问题?
当我使用此代码时:
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));
这是我在控制台中得到的结果:
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> ]```
1个回答
问题是 XP.findOne 函数是异步的,并且您向其传递了一个回调。因此它不会等待所有操作完成后才
return returnedArray
。
您应该在 findOne 上使用 await
await XP.findOne(...
,然后您的代码将按照您期望的方式工作。
如果您想查看,这里有一个很棒的 async await 的 mozilla 链接 https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
Sumit
2020-06-19