Search code examples
javascriptnode.jsdiscorddiscord.jses6-promise

Problem with discord embeds, and [object Promise]


I'm coding a discord bot, and I need to know who reacted to a specified message, and put they usernames in a discord embed.

Here's the code:

MSG.messages.fetch({ around: GameID, limit: 1 }).then((msg) => {
  fetchedMsg = msg.first();
  let MessageOBJ = fetchedMsg.reactions.cache.get("👍");

  const embed = new Discord.MessageEmbed()
    .setTitle("All players here !")
    .setDescription("Here's all of the players for this game")
    .addField(
      "Players",
      MessageOBJ.users.fetch().then((users) => {
        users.forEach((element) => {
          `${element.username}\n`;
        });
      })
    );

  fetchedMsg.edit(embed);
});

However, the bot displays [object Promise] in the Players category of the embed.


Solution

  • I'm no expert in the discord api, however what you are experiencing is likely a problem with promises. The method returns a promise, which likely have the info inside it.

    There are a few ways to solve this. My preferred way is to use await

    const embed = new Discord.MessageEmbed()
        .setTitle('All players here !')
        .setDescription('Here\'s all of the players for this game')
        .addField('Players', await MessageOBJ.users.fetch().then(users => {
            users.map(element => 
                `${element.username}\n`
        )
        }))
    

    As you can see, the addField needs the actual data, not the promise which returns the data.

    To get this to work, you might have to mark your functions as async

    Also, some of your inline functions also looks to have the wrong bracket formatting for what you are trying to achieve.

    Likely the "end result" you are after is something like this:

    MSG.messages.fetch({ around: GameID, limit: 1 })
        .then(async msg => {
            const fetchedMsg = msg.first();
            const MessageOBJ = fetchedMsg.reactions.cache.get("👍");
            const playerNames = await MessageOBJ.users.fetch()
                .then(users =>
                    users.map(element =>
                        `${element.username}\n`
                    )
                )
            const embed = new Discord.MessageEmbed()
                .setTitle('All players here !')
                .setDescription('Here\'s all of the players for this game')
                .addField('Players', playerNames)
            fetchedMsg.edit(embed);
        });