Solution for Discord.js – Continue loop for next users from Reaction.users.fetch().each((user) => {…});
is Given Below:
Heres a code snippet under client.on('ready', async() => {...});
:
this.MyServer = await client.guilds.fetch('MyServer ID here').catch(error => { console.log(error) });
this.MyRole = await this.Server.roles.cache.find((role) => role.name == `MyRole name here`);
this.MyChannel = await client.channels.fetch('MyChannel ID here').catch(error => { console.log(error) });
this.MyMessage = await this.RoleChannel.messages.fetch('MyMessage ID here').catch(error => { console.log(error) });
this.MyEmojiReaction = await this.MyMessage.reactions.cache.get('MyEmoji ID here');
this.ReactingUsers = await this.MyEmojiReaction.users.fetch();
this.ReactingUsers.each(async (user) => {
if (!this.MyServer.members.cache.get(user.id)) return;
if (!user.bot) {
try {
const member = await this.MyMessage.guild.members.fetch(user.id);
member.roles.add(this.MyRole);
} catch (error) {
console.log(error);
return;
}
}
});
As the bot starts, it should check for the reaction, this.MyEmojiReaction
in the message, this.MyMessage
in the channel, this.MyChannel
, and add the reacting users stored in this.ReactingUsers
to the role, this.MyRole
. It is working mostly fine except one problem.
The first line if (!this.MyServer.members.cache.get(user.id)) return;
in this.ReactingMembers.each(async (user) => {..}
is responsible to return from the function if the user from this.ReactingMembers
is not present in this.MyServer
and it does but as it returns, the function never executes for the next users in this.ReactingMembers
, maybe because it returns from the entire loop. I want to continue the loop for the next users.
If i understand it correctly, you should use continue
.
It will instead go to the next iteration, and the next User in the array.
In your case, instead of this:
if (!this.MyServer.members.cache.get(user.id)) return;
You should do it like this:
if (!this.MyServer.members.cache.has(user.id)) continue;