Reputation: 35
In my app, is there a way that I can make a while loop not go through unless everything inside it has been ran through once? This is what I'm doing:
while (runs > 0) {
message.channel.send("run")
await collector.on('collect', async msg => {
if (msg.content.startsWith("success")) {
succeeds += 1
}
runs -= 1
}
If I have runs set to 10, each time the if statement got triggered it adds to succeeds variable. At the end when its done, console.log(succeeds)
shows 18-22 instead.
The point of this while loop is to have it execute something x times.
Upvotes: 0
Views: 54
Reputation: 1339
You can use async/await and promises to make your while loop wait. Use the resolve of promise to make your single iteration pause.
const waitingWhileFunction = async () => {
let runs = 10;
while (run > 0) {
await new Promise((resolve, reject) => {
collector.on('collect', (msg) => {
if (msg.content.startsWith('success')) {
succeeds += 1;
}
resolve();
});
});
runs -= 1;
}
};
waitingWhileFunction();
Upvotes: 1
Reputation: 2679
You can catch error inside the loop so that it doesn't break. Example:
let loop = true;
while(loop) {
try {
// do something 1
// do something 2
// do something N
loop = false;
} catch(e) {
// Did not succeed. Run again
}
}
Upvotes: 0