Discord Bot with JavaScript: For Loop Iteration Issue

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

I had a similar issue when working on a Discord bot. In my case, the problem was that the asynchronous callbacks did not capture the correct iteration values because of scoping issues. Although your code already uses let correctly, there could be unexpected behavior if modifications are made elsewhere. I ended up restructuring my code by extracting the API call into a separate function, which made it clearer and ensured that every variable was correctly captured. This also helped me in debugging and testing individual components reliably.