【问题标题】:Await is only valid in async function for bulkDeleteAwait 仅在 bulkDelete 的异步函数中有效
【发布时间】:2020-04-15 19:16:27
【问题描述】:

我正在使用 Discord.js 编写一个 Discord 机器人,并且我正在尝试创建一个 .clear 命令来清除消息。问题是我无法删除消息,因为我在尝试使用 bulkDelete 时收到了await is only valid in async function。我在bot.on('message', msg => { 部分对此进行了编码。这是我的代码:

if (msg.content.startsWith('.clear')) {
    if(msg.member.hasPermission('MANAGE_MESSAGES')) {
      const args = msg.content.split(' ').slice(1);
      const amount = args.join(' ');
      if(!amount) {
        const noNumbers = new Discord.RichEmbed()
          .setColor('#0099ff')
          .setDescription(':no_entry: Vous n\'avez pas précisé combien de messages devraient être supprimés !')
        msg.channel.send(noNumbers)
      }
      if(isNaN(amount)) {
        const notNumber = new Discord.RichEmbed()
          .setColor('#0099ff')
          .setDescription(':no_entry: Ce paramètre n\'est pas un nombre !')
        msg.channel.send(notNumber)
      }
      if(amount > 100) {
        const tooMuch = new Discord.RichEmbed()
          .setColor('#0099ff')
          .setDescription(':no_entry: Vous ne pouvez pas supprimer plus de 100 messages à la fois !')
        msg.channel.send(tooMuch)
      }
      if(amount < 1) {
        const tooLess = new Discord.RichEmbed()
          .setColor('#0099ff')
          .setDescription(':no_entry: Vous ne pouvez pas supprimer moins d\'un message !')
        msg.channel.send(tooLess)
      }
      else {
          await msg.channel.messages.fetch({limit: amount}).then(messages => {
            msg.channel.bulkDelete(messages)        
          });
        }
      }
    }

谢谢! (不要介意嵌入描述,我是法国人)

【问题讨论】:

  • 既然已经使用then 语法,为什么还要使用await
  • @Bergi 如果他返回的承诺本身返回一个新的承诺,这是合法的。但是,您是对的,还不如再链接另一个。我实际上认为这个函数不需要使用异步等待。如果它返回一个值,它可能更容易阅读,但您基本上是将操作推迟到消息获取完成之后。

标签: javascript async-await discord


【解决方案1】:

试试:

bot.on('message', async (msg) => {
  // your code
}

【讨论】:

  • 删除我的答案,因为@Christopher Stevens 先到了那里。只是为了扩展:使用 await 本质上可以让您在表达式返回承诺时暂停函数的执行。问题是调用函数需要是异步的
  • 当我尝试这个时,我得到另一个错误:UnhandledPromiseRejectionWarning: TypeError: msg.channel.messages.fetch is not a function
  • @KrystStalin 我相信这意味着您已经取得了进一步的进展(异步问题已解决),现在有一个单独的问题需要解决。例如,您可能想尝试msg.channel.fetchMessages() 而不是msg.channel.messages.fetch()(只是根据Google search 猜测,可能会过时)
猜你喜欢
  • 1970-01-01
  • 2020-09-07
  • 2019-09-12
  • 1970-01-01
  • 2020-08-13
  • 2022-06-18
  • 2020-12-23
  • 2019-06-14
  • 1970-01-01
相关资源
最近更新 更多