javascript - SyntaxError:非法返回语句 [Discord.js]
问题描述
以下行引发错误:
if (!client.commands.has(command)) return;
我正在关注本教程=教程
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require("./config.json")
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.content === `${prefix}serverinfo`) {
message.channel.send(message.guild.name)
message.channel.send(`Total Members: ${message.guild.memberCount}`)
} else if (message.content === `${prefix}me`) {
message.channel.send(`Username: ${message.author.username}`)
message.channel.send(`ID: ${message.author.id}`)
} else if (message.content === `${prefix}boi`) {
message.channel.send('BOI')
}
});
if (!client.commands.has(command)) return;
解决方案
您不能return
在顶级范围内,return
必须在函数内。
您可以将逻辑放在if
语句中
if (client.commands.has(command)) {
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
}
或者将逻辑包装在函数中,IIFE可能是一个不错的选择:
(() => {
if (!client.commands.has(command)) return;
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
})();
推荐阅读
- python-3.x - 'float' 对象没有属性 'utcoffset'", '发生在索引 30852'
- javascript - 在 React Native 中不惜一切代价防止导航返回
- php - PHP Zip 下载为空
- google-app-maker - 当我尝试将文件上传到 Google Drive 文件夹时,不断收到“服务器被拒绝”
- wpf - “FrameworkAppContextSwitches”类型不可访问
- google-cloud-shell - 我不小心在我的 CloudShell .bashrc 中添加了一个“退出”,无法返回编辑它,它立即退出
- powershell - PowerShell Job.Progress 包含多个对象
- reactjs - 当在地图函数中初始化的孩子的父状态发生变化时,如何更新孩子的道具?
- html - 如何确保从数据库传递的内容不会导致我的表格高度增加超过一定高度?
- android - 无法从 Android 平板电脑中声明 WebUSB 接口(设备或资源繁忙 16)。Windows 工作正常