不和谐嵌入的问题,以及 [object Promise]

Problem with discord embeds, and [object Promise]

我正在编写一个 discord 机器人,我需要知道谁对特定消息做出了反应,并将他们的用户名放入 discord 嵌入中。

代码如下:

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

但是,机器人在嵌入的播放器类别中显示 [object Promise]

尝试在创建嵌入之前启动承诺。

function promise() {
  return new Promise((resolve, reject) => {
    resolve(['User 1', 'User 2', 'User 3']);
  });
}

console.log(promise().then((result) => result)) // putting the promise inside
promise().then((result) => console.log(result)) // initiating it outside

// also, make sure to use `Array.map` instead of `Array.forEach`
promise().then((result) => console.log(result.forEach((user) => `${user}\n`)))
promise().then((result) => console.log(result.map((user) => `${user}\n`)))

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

我不是不和谐方面的专家 api,但是您遇到的可能是 promise 的问题。方法 returns 一个承诺,其中可能包含信息。

有几种方法可以解决这个问题。我的首选方法是使用 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`
    )
    }))

如您所见,addField 需要实际数据,而不是 returns 数据的承诺。

要使其正常工作,您可能必须将函数标记为 async

此外,您的某些内联函数看起来也有错误的括号格式,无法满足您要实现的目标。

您所追求的“最终结果”可能是这样的:

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