【问题标题】:How do I return text from a function?如何从函数返回文本?
【发布时间】:2021-09-06 12:39:40
【问题描述】:

我知道这是一个非常愚蠢的问题,但我很累,似乎无法想出解决这个问题的想法:

            const fetched = filteredResult.sort((a, b) => b.data - a.data).slice(0, 10)
            const fetchUser = async id => client.users.fetch(id);
            message.channel.send(
                new Discord.MessageEmbed()
                    .setTitle("Pp Leaderboard")
                    .setColor(roleColor === "#000000" ? "#ffffff" : roleColor)
                    .setDescription(
                        fetched.map((v, i) => {
                            v.ID = v.ID.replace("globalMessages_", "");

                            return `#${i + 1} **${fetchUser(v.ID).then(user => { user.tag })}** with ${commaNumber(v.data)} thanks\n`;
                        })
                    )
            )

这是一个感谢排行榜命令^^^。 它显示了全球前十名的排名。

不要担心其他的东西——只关心 fetchUser(v.ID)...一旦我执行命令,它会返回一个嵌入的文本,然后在 fetchUser 的地方它会显示 [Object promise]。

我希望它以某种方式返回那个不和谐用户的标签。提前谢谢!

【问题讨论】:

标签: javascript discord.js


【解决方案1】:
const fetchUser = async id => client.users.fetch(id);

fetchUser 是一个async 箭头函数。异步函数总是返回一个承诺。要获得价值,您必须await fetchUser(...)

.setDescription(
  // Changed the `map()` callback to an async function so we can use
  // `await`. This will return an array of promises, so we need to wrap
  // the `map()` result with `Promise.all()`.
  await Promise.all(fetched.map(async (v, i) => {
    v.ID = v.ID.replace("globalMessages_", "");
    return `#${i + 1} **${(await fetchUser(v.ID)).tag}** with ${commaNumber(v.data)} thanks\n`;
  }))
)

这假设您可以在程序的当前上下文中使用await

【讨论】:

  • 非常感谢,我忘了!
猜你喜欢
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 2018-08-22
相关资源
最近更新 更多