因为没有明显原因的循环停止

时间:2017-07-18 13:36:43

标签: javascript node.js discord

我在Discord bot上运行了以下setInterval

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);

一切都按预期工作,除了在第93次迭代之后循环停止并且没有其他任何执行(直到setInterval的下一次迭代发生)。这很奇怪,因为guilds数组中有超过400个对象,我甚至检查了第94个元素,用于我在循环中进行的检查,并且它通过了所有这些。可能导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:4)

如果循环退出而不是行

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

正在运行。

所以我猜你想要继续循环,所以你应该使用continue来退出那个迭代,而不是return