Tenclea
Tenclea

Reputation: 1464

Wait for event before 'for' loop continues

I'm still working on a Node.js Discord bot, and I would like to know if something is actually possible:

I have a list of players, from which I choose one at random inside a for loop, like this:

let players=['foo', 'bar'];
for (let round = 0; round < players.length; round++) {
    let randPlayer = players[Math.floor(Math.random() * players.length)];

    // Events
}

After that, I'm awaiting for a reaction on a sent message using Discord.js' collectors:

// Events
let msg = await message.channel.send('Message Here');
await msg.react('✔'); await msg.react('❌');

const filter = (reaction, user) => (user.id === randPlayer);
const ansCollector = await msg.createReactionCollector(filter, { time: 15000 });

await ansCollector.on('collect', async (reaction) => {
    // Do something
});

The thing is, that the collector is never able to collect because of the for loop skipping to another player before the 'collect' event is fired.

Do you have any alternatives for this code?

Have a nice day :D

Upvotes: 0

Views: 999

Answers (1)

Ayush Gupta
Ayush Gupta

Reputation: 9295

Wrap your EventEmitter listener in a Promise which resolves once per player, and await on the promise.

for (let round = 0; round < players.length; round++) {
    let randPlayer = players[Math.floor(Math.random() * players.length)];

    await new Promise(resolve => ansCollector.once('collect', async (reaction) => {
        resolve(reaction);
    });
    // Events
}

Upvotes: 1

Related Questions