javascript - 从不和谐机器人的 javascript 中的 fs.readdir 函数中断 for 循环
问题描述
所以我一直在搜索很多网站和文章,但没有很好的解释如何做到这一点
fs.readdir(`./commands`, (err, folders) => {
let loop = true;
for (const folder of folders) {
fs.readdir(`./commands/${folder}`, (err, files) => {
if (files.includes(`${command.infos.name}.js`)) {
delete require.cache[require.resolve(`../${folder}/${command.infos.name}.js`)];
client.commands.delete(commandName);
try {
const newCommand = require(`../${folder}/${command.infos.name}.js`);
message.client.commands.set(newCommand.infos.name, newCommand);
message.channel.send(`Command \`${newCommand.infos.name}\` was reloaded!`);
return false;
} catch (error) {
console.error(error);
return message.channel.send(`There was an error while reloading a command \`${command.infos.name}\`:\n\`${error.message}\``);
}
return false;
} else {
return true;
}
});
if (result === false) {
break;
}
}
});
我想要做的是在if (files.includes(`${command.infos.name}.js`))
为真时打破for循环,这样如果程序已经找到它想要重新加载的文件,它就不会继续检查其他文件夹。
我想使用fs.readdir
它是因为它是一个异步函数,但由于它是一个异步函数,我无法从fs.readdir
. 我尝试过使用 Promise,但我似乎无法理解它。所以我希望是否有其他方法可以在for
不删除代码的异步部分的情况下打破循环。
解决方案
我找到了答案,这就是答案
fs.readdir(`./commands`, async(err, folders) => {
for (const folder of folders) {
const files = await fs.promises.readdir(`./commands/${folder}`);
if (files.includes(`${command.infos.name}.js`)) {
delete require.cache[require.resolve(`../${folder}/${command.infos.name}.js`)];
client.commands.delete(commandName);
try {
const newCommand = require(`../${folder}/${command.infos.name}.js`);
message.client.commands.set(newCommand.infos.name, newCommand);
message.channel.send(`Command \`${newCommand.infos.name}\` was reloaded!`);
} catch (error) {
console.error(error);
message.channel.send(`There was an error while reloading a command \`${command.infos.name}\`:\n\`${error.message}\``);
}
break;
}
}
});
推荐阅读
- nvidia - 为什么跨 NUMA 节点的 NVIDIA GPU 可以启用 P2P?
- c# - 在 ASP.NET Webform 中使用 JQuery 和 Ajax 的 CRUD
- visual-studio - Visual Studio 在构建后执行联动
- javascript - 在 Stripe 付款前查找国家/地区代码
- c# - 从 WPF 访问 Windows 通知
- rest - 如何在 GET 端点中绑定 url 编码参数?
- python - 当索引的范围是 [X, Y] 时,为什么我会收到“IndexError:索引 20 超出轴 1 的范围,大小为 20”?
- angular - 打字稿 - 无法读取未定义的属性“推送”
- reactjs - 相对简单的 React App 未在 AWS Amplify 上正确部署
- javascript - 如何让触摸屏识别 .focus 和 .active 状态?