Q:

jQuery JSON queries - order is random

Look at this Codepen:
http://codepen.io/anon/pen/mPeqBQ
var streamers = ["WagamamaTV", "losty123", "BlackDotATV", "Dendi", "VITALIC_DOTA2", "Singsing", "zonixxcs", "Attackerdota", "purgegamers", "Mikerina","ESL_LOL","jcarverpoker", "gnumme"];

The code query looks as follows:
$.each(streamers, function(key, value) {
    $.getJSON('https://api.twitch.tv/kraken/streams/' + value, function(channel) {
      if (channel["stream"] == null) {
        // ADD TABLE ROW WITH DATA (for details see codepen
      } else {
        // ADD TABLE ROW WITH DATA (for details see codepen)
      }
    });
});

The Order in which the table rows are added is more or less random. Can I influence this order somehow so that it preserves the original order given in the array "streamers"? Just go to the codepen and refresh it a few times, you'll see what I mean.
Thanks

A:

This is because your AJAX calls are all running at the same time!  They may not finish in the same order.  One may be a bit faster or slower, so the order isn't the same.
To fix this, you can use promises.  Basically, wait until all requests are done, then display the results in the same order.
P.S. You can use channel.stream instead of channel["stream"].
// Array shortened for example
var streamers = ["WagamamaTV", "losty123", "BlackDotATV", "Dendi"],
    promises = [];

$.each(streamers, function(key, value){
    // Push the promise into the array
    // We'll take care of the callback and building the table later
    promises.push($.getJSON('https://api.twitch.tv/kraken/streams/' + value));
});

// Now wait until *all* of the requests are done
$.when.apply($, promises).then(function(){
    // This function is passed one argument for each AJAX call,
    // they are passed in order.  So, we can loop over `arguments`
    // to get them in order
    $.each(arguments, function(key, val){
        // Each parameter is actually an array, it's what is normally returned
        // from an AJAX call: `[ data, statusText, jqXHR ]`
        var channel = val[0],
            value = streamers[key];

        if (channel.stream == null) {
            // ADD TABLE ROW WITH DATA (for details see codepen)
        } else {
            // ADD TABLE ROW WITH DATA (for details see codepen)
        }
    });
});

Updated codepen: http://codepen.io/anon/pen/GZpyXZ
Docs for $.when (See "Examples"): http://api.jquery.com/jQuery.when/

