So I have been searching many websites and articles but there are no good explanation on how to do it
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;
}
}
});
What I'm trying to do is to break the for loop when the if (files.includes(`${command.infos.name}.js`)) is true so that the program won't continue to check other folder if it already find the file that it wants to reload.
I want to use fs.readdir because it's an asynchronous function but since it's an asynchronous function I can't change any value from the outside of the fs.readdir. I have tried using promise but I can't seem to understand it. So I'm hoping if there is other method to break the for loop without removing the asynchronous part of the code.
fs.readdir()operations are all running in parallel, so all the other ones have already been started by the time you even want to break the loop. If you want to sequence the operations in your loop, then you will want to useawait fs.promises.readdir()instead of the way you have it structured now.fs.promises.readdir()on my code?