I’m building a Discord bot in JavaScript and running into a weird problem with array iteration. When I try to loop through an array and make API calls, the loop variable seems to get messed up inside the callback function.
Here’s my code:
const Discord = require('discord.js');
const fetch = require('node-fetch');
const TOKEN = "your_bot_token";
const API_KEY = "?key=your_api_key";
const STREAM_API = "https://api.example.com/status/";
const client = new Discord.Client();
var streamers = ["streamer_a", "streamer_b", "streamer_c"];
client.login('bot_token_here');
client.on("message", function(msg) {
if (msg.content === "!status") {
for (var j = 0; j < streamers.length; j++) {
fetch(STREAM_API + streamers[j] + API_KEY)
.then(response => response.json())
.then(data => {
if (data.online == false) {
msg.reply(streamers[j] + ' is offline');
} else {
msg.reply(streamers[j] + ' is online');
}
});
}
}
});
The strange thing is that when I log the loop counter before the API call, it shows 0, 1, 2 correctly. But inside the callback function, it always shows 3. This makes the bot display “undefined is online/offline” instead of the actual streamer names. The loop itself works fine, but something happens with the variable inside the async callback. Anyone know what’s causing this behavior?