如何绕过.forEach循环,这样我才不会向api发送垃圾邮件?

时间:2019-07-06 19:57:55

标签: node.js discord.js

我正在执行命令,其中将特定角色添加到所有成员。 问题在于,.forEach循环对于API来说太快了。

我知道我可能必须以某种方式使用setIntervall解决此问题。

module.exports.run = async (bot, message, args, level) => {
    if (!args || args.length < 1) return message.reply("Must provide a role to give. Derp.");


    let role = message.guild.roles.find(r => r.name == args[0])

    if (!role) return message.channel.send(`**${message.author.username}**, role not found`)

        let msg = await message.channel.send("Ur lazy")

        message.guild.members.filter(m => !m.user.bot).forEach(member => member.addRole(role))


        message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
        msg.delete();

}

目前,这只会产生超时错误,这是非常不希望的,所以我需要做同样的事情,但要慢一些:)

1 个答案:

答案 0 :(得分:0)

你能解释一下吗? 如果您要等到所有成员都添加完毕,可以使用:


module.exports.run = async (bot, message, args, level) => {
    if (!args || args.length < 1) return message.reply("Must provide a role to give. Derp.");


    let role = message.guild.roles.find(r => r.name == args[0])

    if (!role) return message.channel.send(`**${message.author.username}**, role not found`)

        let msg = await message.channel.send("Ur lazy")

        const members = message.guild.members.filter(m => !m.user.bot);
     for(let i = 0; i < members.length; i++){
       await new Promise(resolve => setTimeout(() => {
           members[i].addRole(role)
           resolve();
         },1000))
     }



        message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
        msg.delete();

}