0

I wrote this code:

$(document).ready(function() {
  var streamNames = [
    "ESL_SC2",
    "OgamingSC2",
    "nl_kripp",
    "nl_kripp",
    "freecodecamp",
    "storbeck"
  ];

  for (var i = 0; i < streamNames.length; i++) {
    $.getJSON(
      "https://api.twitch.tv/kraken/streams/" +
        streamNames[i] +
        "?client_id=.......",
      function(data) {
        if (data.stream == null) {
          $("#status" + [i]).text("Offline");
        } else {
          $("#status" + [i]).text("Online");
          console.log(i)
        }
     ;

There are 2 problems occurring here.

1.The JSON data comes randomly and not in the order of the array.

2.i is always 6 (last count) in the for expression.

Anyone could help me out figure out why this is happening?

wersimmon
  • 2,809
  • 3
  • 22
  • 35
Kostis
  • 119
  • 1
  • 12
  • JSON has no 'order' (it's an unordered collection), and there are 6 streams, so you get 6 in `i`. Neither of those seem to be a 'problem' to me; it's how your code is designed to work. – Obsidian Age Oct 18 '17 at 22:17
  • but it should get the first streamer [i=0], second streamer [i=1]and etc...but i get something like 4,3,5,6,1,2 streamers when i log it – Kostis Oct 18 '17 at 22:19
  • The problem is that you're sending out the requests one after another, but not checking when the data actually comes back. If you specifically want to check them in sequential order, you're looking to do a [**callback**](http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/) after each request in which you make the next request. – Obsidian Age Oct 18 '17 at 22:20
  • I will check on that! – Kostis Oct 18 '17 at 22:21
  • `$.getJSON` is **asynchronous** so the loop will have completed before the results are returned from requests. That means `i` will already be at it's max. Use a closure instead of `for()` loop. Easy one is use `$.each()` – charlietfl Oct 18 '17 at 23:03
  • Thanks. I already found a better way to address the api with: https://wind-bow.glitch.me/twitch-api/streams/"+streamNames[i]. I will give $.each() a go aswell. – Kostis Oct 18 '17 at 23:09

1 Answers1

0

var hoists, so your code is equivalent to

var i;
for (i = 0;...

You can fix this by using let here. for (let i = 0; ...

The JSON can never be guaranteed to come back in any order. Such is the nature of the event loop and asynchronicity. But With the let at least the is should be unique for each block of the loop.

Austin Ezell
  • 753
  • 4
  • 12