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

运行Discord.js机器人代码报await仅支持async函数语法错误如何修复

问题修复方案

错误原因

await是JavaScript异步语法的关键字,仅允许在两种场景下使用:

  • 标记了async关键字的异步函数内部
  • ES模块的顶层作用域

你当前代码中interactionCreate事件的回调函数是普通同步函数,内部调用interaction.reply时使用了await,不符合语法要求因此触发报错。

修复步骤

只需要给interactionCreate的事件回调函数添加async标记即可,修改后的代码段如下:

// 仅需要在回调参数前增加async关键字
Client.on("interactionCreate", async interaction => {
    if(interaction.isCommand()){
        if(interaction.commandName === "ping"){
            interaction.reply("pong");
        }
        else if (interaction.commandName === 'server'){
            await interaction.reply(`Server name:${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
        }
        else if (interaction.commandName === 'user'){
            await interaction.reply("Your tag:" + interaction.user.tag + "\nYour id:" + interaction.user.id);
        }
    }
});

其他可优化的代码问题(可选)

  • 你在ready事件中调用commands.create(data),但代码中没有定义data变量,你已经提前声明了commands数组,这里应该改为传入commands变量
  • 重复监听了4次messageCreate事件,可以合并为一个事件回调,按顺序判断指令即可,减少不必要的事件绑定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:48:03