Trying to make a series of Ajax requests, and need some advice

Trying to make a series of Ajax requests, and need some advice
0

#1

I’m having trouble figuring this out. I can make an Ajax to check the current streaming status of a channel with this function:

$(document).ready(function() {

var channelsArray = [“test_channel”, “freecodecamp”, “ESL_SC2”, “OgamingSC2”, “cretetion”, “storbeck”, “habathcx”, “RobotCaleb”, “chewieMelodies”];

function getStream(id) {
$.ajax({
url: “https://api.twitch.tv/kraken/streams/” + channelsArray[id],
type: “GET”,
dataType: “json”,
headers: { ‘Client-ID’: ‘atxj9cwb80w0md74abvc6c3g0le21vr’ },
success: function (data) {
if (data.stream == null) {
console.log(“offline”)}
else {
console.log(“currently streaming”)};
}
});
};

getStream(id);
;

});

It works for one channel, but then when I try to get it to go though all the channels with loop like this, it won’t work:

for (id=0;id<channelsArray;id++) {
getStream(id);
};

I thought it had something to do with it being asynchronous, so if the request doesn’t get a response right away it just keeps going…I’m missing something, or not understanding something but I don’t know what it is. How I can I fix this code so that it will go through all the channels and tell me their stream status? Any help or hints would be appreciated. Thanks!

David


#2

I think your for loop should look like this:

`for(var id=0;id<channelsArray.length;id++){
      getStream(id);
 }`

You forget to specify the length property on your array that’s why the loop is getting terminated after just passing the first channel.

`


#3

Try using .forEach on the array of channels instead of using a for-loop. With that approach, you’ll have to modify getStream(id) into getStream(name). Then replace channelsArray[id] in the url with name.

Or try initializing id in the for loop header with the let keyword.

EDIT
@kunalgupta05 I didn’t see the missing .length :sweat_smile:. That might work.


#4

Hahaha…trust me i also spent 15 minutes debugging the code in my mind before i came to know that he’s missing the length property :smiley:


#5

Haha…that’s embarrassing. I should’ve been able to figure that out on my own. I stared at it for a pretty long time too! Thanks!


#6

Happens to all of us…!!:smiley:


#7

It’s happened to me before, but usually I catch before I advertise it to the world! Oh well, a little humility never hurt anyone.


#8

Haha…yeah it does make you a better developer…!!


#9

I suppose, no pain, no gain! There is definitely some pain, but it’s a good pain, especially when I finally solve whatever the problem (or in this case get someone to solve it for me).