#Waiting on while loop

3 messages · Page 1 of 1 (latest)

stiff owl

Hello, I would ask. I have this code:

console.log("- starting winners lottery");
while (this.winners.length < this.winnersCount) {
    const random = Math.floor(Math.random() * this.entries.length);
    let enter = this.entries.at(random);
    console.log(random, enter);
    if (!enter) continue;
    if (!this.winners.find((value) => value === enter?.userId)) {
        this.winners.push(enter.userId);
        return;
    }
}
console.log("- outputing winners");
let formatWinners = ``;
await this.winners.forEach(async (value, index) => {
    const userWinner = await container.client.users.fetch(value);
    formatWinners =
        formatWinners +
        `${userMention(value)} ||${
            userWinner.username
        } - (${value}) (${index})||\n`;
});

But my main problem is I have to wait to finish while loop to format winners. But how I could do that? Can someone tell me any idea?

hazy ocean

how is that a problem? your while seems to be fully synchronous, you're already waiting for it to complete

the issue is in your forEach being asynchronous, you should instead use a for..of or map + Promise.all + join to get linear behavior