主动返回undefined是什么原因呢?

What is the reason for returning undefined voluntarily?

为什么要 return 未定义? 例如在这个 discord.js 代码示例中

client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;

const { commandName } = interaction;

if (commandName === 'ping') {
    await interaction.reply('Pong!');
} else if (commandName === 'server') {
    await interaction.reply('Server info.');
} else if (commandName === 'user') {
    await interaction.reply('User info.');
}
});

return未定义通常不是有问题的标志吗?那我为什么要 return undefined 自愿呢? 任何更清楚的例子将不胜感激。

这与 return 未定义无关,return 语句只是一个 guard clause。 保护子句的主要目的是在不满足某些条件时退出函数。

在这种情况下,保护子句的原因是只允许命令交互通过,而忽略按钮或选择菜单交互。