Rodrigo Leite
Rodrigo Leite

Reputation: 596

for...of loop halts for no apparent reason

I have the following setInterval running on a Discord bot:

client.setInterval(async () => {
    try {
        const response = await fetch('http://pso2.kaze.rip/eq/');
        if (response.status !== 200) return;

        const data = await response.json();
        const cache = JSON.parse(await fs.readFile("./cache.json"));

        if (data[0]["time"] !== cache["time"]) {
            const guilds = client.guilds.filter(guild => { return client.provider.get(guild, "alerts") });

            let i = 0;
            for (let guild of guilds) {
                i = i + 1;
                let settings = await client.provider.get(guild[1], "alerts");
                let eqs = data[0]["eqs"].filter(item => { return settings["ships"].includes(item["ship"]) });
                let format = [];

                if (!client.channels.get(settings['channel'])) return;
                let channel = client.channels.get(settings['channel']);

                if (eqs.length <= 0) return;
                if (eqs.length > 0 && eqs.length !== 10) {
                    for (let eq of eqs) {
                        format.push(`\`SHIP ${eq['ship']}:\` ${eq['name']} (${eq['jpName']})`);
                    }
                }
                else {
                    format.push(`\`ALL SHIPS:\` ${eqs[0]['name']} (${eqs[0]['jpName']})`);
                }

                let time = moment(data[0]["when"]);
                let string = `:watch:**IN 40 MINUTES:** (${time.format("HH:mm")} JST)\n${format.join('\n')}`;

                if (channel.type == "text" && channel.permissionsFor(client.user).has("SEND_MESSAGES")) {
                    //await client.channels.get(settings['channel']).send(string);
                    console.log(`${i} Sending alert to guild ${guild[1]}`);
                }
                else {
                    console.log(`${i} Skipping guild ${guild[1]}`);
                }
            }

            console.log('writing file...');
            await fs.writeFile("cache.json", `{ "time" : "${data[0]["time"]}" }`);
            console.log('done');
        }
    } catch (err) {
        console.error(err);
    }
}, 10000, client);

Everything is working as expected, except that after the 93rd iteration the loop stops and nothing else is executed (until the next iteration of the setInterval happens). This is odd because the guilds array has over 400 objects in it, and I even checked the 94th element for the checks I'm doing inside the loop and it passed all of them. What could be causing this?

Upvotes: 0

Views: 67

Answers (1)

epascarello
epascarello

Reputation: 207527

If the loops exits than the line

if (!client.channels.get(settings['channel'])) return;

is running.

So I am guessing you want to keep on looping so you should be using continue to exit that iteration, not return

Upvotes: 4

Related Questions