Building a Discord bot in JavaScript. My for loop index seems incorrect when used with asynchronous API calls. The sample code below demonstrates the issue:
const discord = require('discord.js');
const fetchData = require('node-fetch');
const API_ENDPOINT = "https://api.example.com/streams?user=";
const botSecret = "your_bot_token";
const streamers = ["alpha123", "beta456", "gamma789"];
const client = new discord.Client();
client.login(botSecret);
client.on('message', message => {
if (message.content === "!status") {
for (let idx = 0; idx < streamers.length; idx++) {
fetchData(API_ENDPOINT + streamers[idx])
.then(res => res.json())
.then(result => {
if (!result.active) message.reply(`${streamers[idx]} is offline`);
else message.reply(`${streamers[idx]} is online`);
})
.catch(err => console.error(err));
}
}
});