You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用embed编辑Discord消息时正确等待Promise.all异步任务完成

问题原因

你遇到的错误来自两个核心的异步逻辑错误:

  • 遍历reaction的map回调是异步函数,会返回一组Promise,你没有等待这组Promise执行完成就直接构建Embed,此时usersThatReacted数组还没填充完成
  • await关键字只能在标注了async的函数内部使用,你直接在普通的then回调里用await会触发未定义错误

修正后的完整代码

// 收集所有反应处理的异步Promise
const reactionPromises = message.reactions.cache.map(async (reaction) => {
  if (reaction.emoji.name !== '👎') return [];
  const reactedUsers = await reaction.users.fetch();
  // 直接返回当前反应对应的所有db查询Promise
  return reactedUsers.map(user => db.get(user.id));
});

// 等待所有反应处理完成,展开拿到所有db查询Promise
const allDbPromises = (await Promise.all(reactionPromises)).flat();
// 等待所有db查询执行完成,拿到最终用户列表
const usersThatReacted = await Promise.all(allDbPromises);

// 构建Embed并编辑消息
message.channel.messages.fetch(message.id).then(async (message) => {
  const exampleEmbed = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setAuthor('.: Отметки активности :.', 'https://emojigraph.org/media/microsoft/crossed-swords_2694-fe0f.png')
    .addFields(
      // 处理空值边界,避免Embed字段为空报错
      { name: '👍', value: usersThatReacted.length ? usersThatReacted.join(', ') : '暂无用户', inline: true },
    )
  await message.edit(exampleEmbed)
  console.log(`Updated the content of a message to ${message.content}`)
}).catch(console.error);

关键修改点

  • 用Promise.all等待所有reaction的异步处理逻辑执行完成,确保所有用户的db查询请求都已经被收集
  • 第二次调用Promise.all等待所有db查询执行完成,拿到实际的用户数据再填充Embed
  • 给then回调加上async标识,允许内部使用await
  • 增加空值判断,当没有用户点反应时用占位符填充字段,避免触发EMBED_FIELD_VALUE错误

内容的提问来源于stack exchange,提问作者Dimooon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:36:03