[英]Return a value from loop in JavaScript?
我正在創建一個 function 來刪除與我的數據庫中所需的“級別”數量不匹配的索引,然后返回該數組。
問題是當我執行cleanWinners(winners, guild).then(res => console.log(res))
時,我收到未定義的消息。 我假設代碼在返回數組之前沒有等待這個 function 結束? 我該如何解決?
當我使用這段代碼時:
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> ]```
問題是 XP.findOne function 是異步的,你向它傳遞了一個回調。 所以它不會等到一切都完成后再return returnedArray
。 您應該在 findOne 上使用 await await XP.findOne(...
然后您的代碼將按照您期望的方式工作。
如果您想查看https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await ,這里有一個很棒的異步等待 mozilla 鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.