(SOLVED) Twitch - Nested getJSON issue?

I’m seeing a strange issue where it seems like my api calls seem to get called out of order. I set up a loop and make an initial call to see if a streamer is online, I then set up an if statement with a path for streamers offline, and another path for streamers online. The offline path makes an another API call using a nested getJSON method. The weird thing is that it seems like the offline getJSON method only gets called after all the online api calls are mad.

Is nesting the getJSON statements causing issues? I can’t quite figure out what the problem is.

$.getJSON is an asynchronous function, so it does not prevent other synchronous code from running while it is awaiting a response back from the an API call. What that means is the for loop finishes before the nested $.getJSON url is created. After the for loop ends, the variable named i has a value of 10, so all of the nested $.getJSON calls uses the following url string build

"https://wind-bow.glitch.me/twitch-api/channels/" + streamers[10] + "?callback=?"

Since there is not an eleventh element in the streamers array, it results in undefined or the following url:


How do you fix this issue? You can use the key word let to declare your i variable in the for loop. The let keyword creates a local block scope for variable i, so that it “remembers” it’s value at the time of the url is built.

Wow, one keyword solves all my issues. Thank you.

So the for loop is finishing even before the nested JSON is called even once?

Just so I understand what is happening with the “let” keyword - it saves the “i” variable value in memory for each nested getJSON request in the loop? Whereas the “var” keyword makes it so the nested getJSON request uses whatever the value is at the time it’s ready to go?

Bonus question:

Why are my rows out of order compared to my array order? Is this because the api request takes a different amount of time for each streamer in the array?

Or at least finishes before the first nested getJSON response comes back.

That is basically what I happens.


There are a couple of reasons why they could be out of order, but how long each response takes to come back is definitely one reason they could be different.