不和谐嵌入和[object Promise]问题

时间:2020-09-18 13:13:54

标签: javascript node.js discord discord.js es6-promise

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

这是代码:

dat

但是,该漫游器在嵌入的“玩家”类别中显示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); });

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-1)

我不是discord api的专家,但是您遇到的问题可能与promise有关。该方法返回一个Promise,其中可能包含信息。

有几种解决方法。我的首选方式是使用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需要实际数据,而不是返回数据的承诺。

要使其正常工作,您可能必须将函数标记为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);
    });