等待事件继续,然后再进行“ for”循环

时间:2020-04-02 12:08:31

标签: javascript node.js loops events discord.js

我仍在开发Node.js Discord机器人,我想知道是否确实可行:

我有一个玩家列表,我可以在for循环中从中随机选择一个玩家,如下所示:

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

    // Events
}

此后,我正在等待使用Discord.js的收集器对发送的消息做出反应:

// 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
});

问题是,由于在触发“收集”事件之前for循环跳到另一个播放器,因此收集器无法收集。

此代码还有其他选择吗?

今天愉快:D

1 个答案:

答案 0 :(得分:1)

将您的EventEmitter侦听器包装在Promise中,该Promise可为每个玩家解决once,并等待诺言。

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
}