I am experiencing a problem, which is, I am sure, related to async/await. So what I am trying to achieve by writing this code is I've earlier created an embed with two buttons, "Approved" and "Denied" (that part of code is not included above).
So what I want to get is that if the user presses the Approve button, the approveChoice variable gets set to "approved," otherwise - "denied." And I have made this if (await approvalChoice != "approved") return; so if the value is not approved, the code will stop executing.
But even with the "await", "approvalChoice" variable is undefined (last line of code)
let senderID = interaction.member.user.id;
const filter = i => (i.customId === `approved_${senderID}` || i.customId === `denied_${senderID}`) && i.user.id === interaction.member.user.id;
const collector = interaction.channel.createMessageComponentCollector({ filter, time: 60000 });
let approvalChoice;
collector.on('collect', async i => {
if (i.customId === `approved_${senderID}`) {
await i.update({ content: 'Operation approved.', components: [] });
approvalChoice = "approved";
collector.stop();
} else if (i.customId === `denied_${senderID}`) {
await i.update({ content: 'Operation cancelled.', components: [] });
approvalChoice = "denied";
collector.stop();
}
});
await collector.on('end', async (collected) => {
if (approvalChoice == "approved") {
await interaction.editReply({content: "_**Processing...**_"});
} else {
await interaction.deleteReply();
}
});
if (await approvalChoice != "approved") return;
Because the code won't stop there and wait your collector ends then continue executing.
You can either put all your thing that should be executed after the button is pressed in the collector.on('end') part, or use awaitMessageComponent instead of the object formed collector. The latter one wrapped the normal collector and you can await it to prevent your code keep executing before the user press the button.