• 1000 Я предполагаю, что код не ждет завершения этой функции перед возвратом массива? Как я могу это исправить?
Когда я использую этот код:
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> ]```